From 594509f3d9b3659d9a97bcfb0cb963eb1e0b9dc9 Mon Sep 17 00:00:00 2001 From: Daniel Cojocea Date: Wed, 18 Sep 2024 17:14:03 -0400 Subject: [PATCH 01/98] Initial styling and structure --- .../Components/Inputs/Autocomplete/index.jsx | 116 ----------------- Client/src/Components/Inputs/Search/index.jsx | 121 ++++++++++++++++++ Client/src/Pages/Monitors/Details/styled.jsx | 3 +- Client/src/Pages/Monitors/Home/index.jsx | 10 +- Client/src/Utils/Theme/lightTheme.js | 3 +- 5 files changed, 132 insertions(+), 121 deletions(-) delete mode 100644 Client/src/Components/Inputs/Autocomplete/index.jsx create mode 100644 Client/src/Components/Inputs/Search/index.jsx diff --git a/Client/src/Components/Inputs/Autocomplete/index.jsx b/Client/src/Components/Inputs/Autocomplete/index.jsx deleted file mode 100644 index 5256efccc..000000000 --- a/Client/src/Components/Inputs/Autocomplete/index.jsx +++ /dev/null @@ -1,116 +0,0 @@ -import { Autocomplete, TextField } from "@mui/material"; -import React from "react"; -import PropTypes from "prop-types"; -import { useTheme } from "@emotion/react"; - -/** - * @example - * - * const options = [ - * { _id: "66d6119ef959cbc681e034f0", name: "Googler" }, - * { _id: "66d6119ef959cbc681e034f0", name: "CNN" }, - * { _id: "66d61a1bf959cbc681e0353f", name: "X Corp." }, - * ]; - * - * - * - */ - -/** - * AutoCompleteField component. - * - * @component - * @param {Object} props - The component props. - * @param {string} props.id - The ID of the autocomplete field. - * @param {string} props.type - The type of the input field (text or number). - * @param {Array} props.options - The options for the autocomplete field. - * @param {string} props.placeholder - The placeholder text for the input field. - * @param {boolean} props.disabled - Indicates if the field is disabled. - * @returns {JSX.Element} The AutoCompleteField component. - */ - -const AutoCompleteField = ({ - id, - type, - options, - placeholder = "Type to search", - disabled, -}) => { - const [value, setValue] = React.useState(); - const [inputValue, setInputValue] = React.useState(""); - const theme = useTheme(); - - return ( - { - setValue(newValue); - }} - inputValue={inputValue} - onInputChange={(event, newInputValue) => { - setInputValue(newInputValue); - }} - options={options} - getOptionLabel={(option) => option.name} - renderInput={(params) => ( - - )} - renderOption={(props, option) => { - const { key, ...optionProps } = props; - return ( -
  • -
    {{option.name}}
    -
  • - ); - }} - slotProps={{ - popper: { - sx: { - "& ul": { p: 0 }, - "& li": { borderRadius: theme.shape.borderRadius }, - }, - }, - paper: { - sx: { - p: 2, - fontSize: 13, - }, - }, - }} - /> - ); -}; - -AutoCompleteField.displayName = "AutoCompleteField"; - -AutoCompleteField.propTypes = { - id: PropTypes.string, - type: PropTypes.oneOf(["text", "number"]), - options: PropTypes.array, - placeholder: PropTypes.string, - disabled: PropTypes.bool, - setWidth: PropTypes.string, -}; - -export default AutoCompleteField; diff --git a/Client/src/Components/Inputs/Search/index.jsx b/Client/src/Components/Inputs/Search/index.jsx new file mode 100644 index 000000000..ab6586119 --- /dev/null +++ b/Client/src/Components/Inputs/Search/index.jsx @@ -0,0 +1,121 @@ +import PropTypes from "prop-types"; +import { Box, ListItem, Autocomplete, TextField } from "@mui/material"; +import { useTheme } from "@emotion/react"; +import SearchIcon from "../../../assets/icons/search.svg?react"; + +const options = [ + "Google", + "Material UI", + "Alias", + "Twitter", + "Discord", + "YouTube", +]; + +const Search = ({ id, sx }) => { + const theme = useTheme(); + + return ( + ( + + + + ), + }} + sx={{ + "& fieldset": { + borderColor: theme.palette.border.light, + borderRadius: theme.shape.borderRadius, + }, + "& .MuiOutlinedInput-root:hover:not(:has(input:focus)):not(:has(textarea:focus)) fieldset": + { + borderColor: theme.palette.border.light, + }, + }} + /> + )} + filterOptions={(options, { inputValue }) => { + const filtered = options.filter((option) => + option.toLowerCase().includes(inputValue.toLowerCase()) + ); + + if (filtered.length === 0) { + return [{ label: "No monitors found", noOptions: true }]; + } + return filtered; + }} + renderOption={(props, option) => { + const { key, ...optionProps } = props; + return ( + + {option.noOptions ? option.label : option} + + ); + }} + slotProps={{ + popper: { + keepMounted: true, + sx: { + "& ul": { p: 2 }, + "& li.MuiAutocomplete-option": { + color: theme.palette.text.secondary, + px: 4, + borderRadius: theme.shape.borderRadius, + }, + "& .MuiAutocomplete-listbox .MuiAutocomplete-option[aria-selected='true'], & .MuiAutocomplete-listbox .MuiAutocomplete-option[aria-selected='true'].Mui-focused, & .MuiAutocomplete-listbox .MuiAutocomplete-option[aria-selected='true']:hover": + { + backgroundColor: theme.palette.background.fill, + }, + "& .MuiAutocomplete-noOptions": { + px: theme.spacing(6), + py: theme.spacing(5), + }, + }, + }, + }} + sx={{ + height: 34, + "&.MuiAutocomplete-root .MuiAutocomplete-input": { p: 0 }, + ...sx, + }} + /> + ); +}; + +export default Search; diff --git a/Client/src/Pages/Monitors/Details/styled.jsx b/Client/src/Pages/Monitors/Details/styled.jsx index 42cc3560d..1e34fbbc9 100644 --- a/Client/src/Pages/Monitors/Details/styled.jsx +++ b/Client/src/Pages/Monitors/Details/styled.jsx @@ -40,8 +40,7 @@ export const ChartBox = styled(Stack)(({ theme }) => ({ fill: theme.palette.text.tertiary, }, "& path": { - transition: "fill 300ms ease", - transition: "stroke-width 400ms ease", + transition: "fill 300ms ease, stroke-width 400ms ease", }, })); diff --git a/Client/src/Pages/Monitors/Home/index.jsx b/Client/src/Pages/Monitors/Home/index.jsx index b66076387..a6518f56b 100644 --- a/Client/src/Pages/Monitors/Home/index.jsx +++ b/Client/src/Pages/Monitors/Home/index.jsx @@ -12,6 +12,7 @@ import StatusBox from "./StatusBox"; import Breadcrumbs from "../../../Components/Breadcrumbs"; import Greeting from "../../../Utils/greeting"; import MonitorTable from "./MonitorTable"; +import Search from "../../../Components/Inputs/Search"; const Monitors = ({ isAdmin }) => { const theme = useTheme(); @@ -26,6 +27,8 @@ const Monitors = ({ isAdmin }) => { let loading = monitorState?.isLoading && monitorState?.monitorsSummary?.monitors?.length === 0; + + console.log(monitorState.monitorsSummary.monitors); return ( {loading ? ( @@ -85,7 +88,8 @@ const Monitors = ({ isAdmin }) => { { > {monitorState?.monitorsSummary?.monitorCounts?.total || 0} - {/* TODO - add search bar */} + + + diff --git a/Client/src/Utils/Theme/lightTheme.js b/Client/src/Utils/Theme/lightTheme.js index c80633a20..5d8d76cde 100644 --- a/Client/src/Utils/Theme/lightTheme.js +++ b/Client/src/Utils/Theme/lightTheme.js @@ -151,12 +151,14 @@ const lightTheme = createTheme({ styleOverrides: { root: { marginTop: 4, + padding: 0, border: 1, borderStyle: "solid", borderColor: border.light, borderRadius: 4, boxShadow: shadow, backgroundColor: background.main, + backgroundImage: "none", }, }, }, @@ -183,7 +185,6 @@ const lightTheme = createTheme({ color: text.secondary, fontSize: 13, margin: 2, - marginBottom: 0, minWidth: 100, "&:hover, &.Mui-selected, &.Mui-selected:hover, &.Mui-selected.Mui-focusVisible": { From 200c5fa52329f74cd3651b582ccc11141b2c8b96 Mon Sep 17 00:00:00 2001 From: Daniel Cojocea Date: Wed, 18 Sep 2024 17:22:58 -0400 Subject: [PATCH 02/98] Hooked up search to state --- Client/src/Components/Inputs/Search/index.jsx | 22 ++++++++----------- Client/src/Pages/Monitors/Home/index.jsx | 10 ++++++--- 2 files changed, 16 insertions(+), 16 deletions(-) diff --git a/Client/src/Components/Inputs/Search/index.jsx b/Client/src/Components/Inputs/Search/index.jsx index ab6586119..b8eaf89b6 100644 --- a/Client/src/Components/Inputs/Search/index.jsx +++ b/Client/src/Components/Inputs/Search/index.jsx @@ -3,25 +3,21 @@ import { Box, ListItem, Autocomplete, TextField } from "@mui/material"; import { useTheme } from "@emotion/react"; import SearchIcon from "../../../assets/icons/search.svg?react"; -const options = [ - "Google", - "Material UI", - "Alias", - "Twitter", - "Discord", - "YouTube", -]; - -const Search = ({ id, sx }) => { +const Search = ({ id, options, value, handleChange, sx }) => { const theme = useTheme(); return ( { + handleChange(newValue); + }} fullWidth freeSolo disableClearable options={options} + getOptionLabel={(option) => option.name} renderInput={(params) => ( { )} filterOptions={(options, { inputValue }) => { const filtered = options.filter((option) => - option.toLowerCase().includes(inputValue.toLowerCase()) + option.name.toLowerCase().includes(inputValue.toLowerCase()) ); if (filtered.length === 0) { - return [{ label: "No monitors found", noOptions: true }]; + return [{ name: "No monitors found", noOptions: true }]; } return filtered; }} @@ -84,7 +80,7 @@ const Search = ({ id, sx }) => { : {} } > - {option.noOptions ? option.label : option} + {option.name} ); }} diff --git a/Client/src/Pages/Monitors/Home/index.jsx b/Client/src/Pages/Monitors/Home/index.jsx index a6518f56b..36921d1f5 100644 --- a/Client/src/Pages/Monitors/Home/index.jsx +++ b/Client/src/Pages/Monitors/Home/index.jsx @@ -1,5 +1,5 @@ import "./index.css"; -import { useEffect } from "react"; +import { useEffect, useState } from "react"; import { useSelector, useDispatch } from "react-redux"; import { getUptimeMonitorsByTeamId } from "../../../Features/UptimeMonitors/uptimeMonitorsSlice"; import { useNavigate } from "react-router-dom"; @@ -19,6 +19,7 @@ const Monitors = ({ isAdmin }) => { const navigate = useNavigate(); const monitorState = useSelector((state) => state.uptimeMonitors); const authState = useSelector((state) => state.auth); + const [search, setSearch] = useState(""); const dispatch = useDispatch({}); useEffect(() => { @@ -28,7 +29,6 @@ const Monitors = ({ isAdmin }) => { monitorState?.isLoading && monitorState?.monitorsSummary?.monitors?.length === 0; - console.log(monitorState.monitorsSummary.monitors); return ( {loading ? ( @@ -118,7 +118,11 @@ const Monitors = ({ isAdmin }) => { {monitorState?.monitorsSummary?.monitorCounts?.total || 0} - + From db4f509f8798ecab3d4b8c8becf23212f0af6308 Mon Sep 17 00:00:00 2001 From: Daniel Cojocea Date: Wed, 18 Sep 2024 17:24:36 -0400 Subject: [PATCH 03/98] Added docs --- Client/src/Components/Inputs/Search/index.jsx | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/Client/src/Components/Inputs/Search/index.jsx b/Client/src/Components/Inputs/Search/index.jsx index b8eaf89b6..a148c4082 100644 --- a/Client/src/Components/Inputs/Search/index.jsx +++ b/Client/src/Components/Inputs/Search/index.jsx @@ -3,6 +3,17 @@ import { Box, ListItem, Autocomplete, TextField } from "@mui/material"; import { useTheme } from "@emotion/react"; import SearchIcon from "../../../assets/icons/search.svg?react"; +/** + * Search component using Material UI's Autocomplete. + * + * @param {Object} props + * @param {string} props.id - Unique identifier for the Autocomplete component + * @param {Array} props.options - Options to display in the Autocomplete dropdown + * @param {string} props.value - Current input value for the Autocomplete + * @param {Function} props.handleChange - Function to call when the input changes + * @param {Object} props.sx - Additional styles to apply to the component + * @returns {JSX.Element} The rendered Search component + */ const Search = ({ id, options, value, handleChange, sx }) => { const theme = useTheme(); @@ -114,4 +125,16 @@ const Search = ({ id, options, value, handleChange, sx }) => { ); }; +Search.propTypes = { + id: PropTypes.string, + options: PropTypes.arrayOf( + PropTypes.shape({ + name: PropTypes.string.isRequired, + }) + ).isRequired, + value: PropTypes.string.isRequired, + handleChange: PropTypes.func.isRequired, + sx: PropTypes.object, +}; + export default Search; From 0aebad25120188ebc00cdec1d8e1259fc8393c40 Mon Sep 17 00:00:00 2001 From: Daniel Cojocea Date: Wed, 18 Sep 2024 20:13:36 -0400 Subject: [PATCH 04/98] Memoized monitor table --- Client/src/Pages/Monitors/Home/MonitorTable/index.jsx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Client/src/Pages/Monitors/Home/MonitorTable/index.jsx b/Client/src/Pages/Monitors/Home/MonitorTable/index.jsx index 5c43ad880..5b5883440 100644 --- a/Client/src/Pages/Monitors/Home/MonitorTable/index.jsx +++ b/Client/src/Pages/Monitors/Home/MonitorTable/index.jsx @@ -16,7 +16,7 @@ import { import ArrowDownwardRoundedIcon from "@mui/icons-material/ArrowDownwardRounded"; import { setRowsPerPage } from "../../../../Features/UI/uiSlice"; -import { useState, useEffect } from "react"; +import { useState, useEffect, memo } from "react"; import { useNavigate } from "react-router"; import { logger } from "../../../../Utils/Logger"; import Host from "../host"; @@ -106,7 +106,7 @@ TablePaginationActions.propTypes = { onPageChange: PropTypes.func.isRequired, }; -const MonitorTable = ({ isAdmin }) => { +const MonitorTable = memo(({ isAdmin }) => { const theme = useTheme(); const navigate = useNavigate(); const dispatch = useDispatch(); @@ -335,7 +335,7 @@ const MonitorTable = ({ isAdmin }) => { ); -}; +}); MonitorTable.propTypes = { isAdmin: PropTypes.bool, From 5b913d9820076cf5f5204d47f0a5eaa393ce29c7 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Thu, 19 Sep 2024 08:18:16 +0800 Subject: [PATCH 05/98] Name anonymous export --- Client/src/Pages/Monitors/Home/MonitorTable/index.jsx | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/Client/src/Pages/Monitors/Home/MonitorTable/index.jsx b/Client/src/Pages/Monitors/Home/MonitorTable/index.jsx index 5b5883440..2fbdf3ca6 100644 --- a/Client/src/Pages/Monitors/Home/MonitorTable/index.jsx +++ b/Client/src/Pages/Monitors/Home/MonitorTable/index.jsx @@ -106,7 +106,7 @@ TablePaginationActions.propTypes = { onPageChange: PropTypes.func.isRequired, }; -const MonitorTable = memo(({ isAdmin }) => { +const MonitorTable = ({ isAdmin }) => { const theme = useTheme(); const navigate = useNavigate(); const dispatch = useDispatch(); @@ -335,10 +335,11 @@ const MonitorTable = memo(({ isAdmin }) => { ); -}); +}; MonitorTable.propTypes = { isAdmin: PropTypes.bool, }; -export default MonitorTable; +const MemoizedMonitorTable = memo(MonitorTable); +export default MemoizedMonitorTable; From 732645929b32b311ecd8d92c1e0ef1a0242c0b8a Mon Sep 17 00:00:00 2001 From: Daniel Cojocea Date: Wed, 18 Sep 2024 20:27:55 -0400 Subject: [PATCH 06/98] Generalized filter --- Client/src/Components/Inputs/Search/index.jsx | 18 +++---- Client/src/Components/Search/index.css | 0 Client/src/Components/Search/index.jsx | 49 ------------------- Client/src/Pages/Monitors/Home/index.jsx | 1 + 4 files changed, 9 insertions(+), 59 deletions(-) delete mode 100644 Client/src/Components/Search/index.css delete mode 100644 Client/src/Components/Search/index.jsx diff --git a/Client/src/Components/Inputs/Search/index.jsx b/Client/src/Components/Inputs/Search/index.jsx index a148c4082..b69b25731 100644 --- a/Client/src/Components/Inputs/Search/index.jsx +++ b/Client/src/Components/Inputs/Search/index.jsx @@ -9,12 +9,13 @@ import SearchIcon from "../../../assets/icons/search.svg?react"; * @param {Object} props * @param {string} props.id - Unique identifier for the Autocomplete component * @param {Array} props.options - Options to display in the Autocomplete dropdown + * @param {string} props.filteredBy - Key to access the option label from the options * @param {string} props.value - Current input value for the Autocomplete * @param {Function} props.handleChange - Function to call when the input changes * @param {Object} props.sx - Additional styles to apply to the component * @returns {JSX.Element} The rendered Search component */ -const Search = ({ id, options, value, handleChange, sx }) => { +const Search = ({ id, options, filteredBy, value, handleChange, sx }) => { const theme = useTheme(); return ( @@ -28,7 +29,7 @@ const Search = ({ id, options, value, handleChange, sx }) => { freeSolo disableClearable options={options} - getOptionLabel={(option) => option.name} + getOptionLabel={(option) => option[filteredBy]} renderInput={(params) => ( { )} filterOptions={(options, { inputValue }) => { const filtered = options.filter((option) => - option.name.toLowerCase().includes(inputValue.toLowerCase()) + option[filteredBy].toLowerCase().includes(inputValue.toLowerCase()) ); if (filtered.length === 0) { - return [{ name: "No monitors found", noOptions: true }]; + return [{ [filteredBy]: "No monitors found", noOptions: true }]; } return filtered; }} @@ -91,7 +92,7 @@ const Search = ({ id, options, value, handleChange, sx }) => { : {} } > - {option.name} + {option[filteredBy]} ); }} @@ -127,11 +128,8 @@ const Search = ({ id, options, value, handleChange, sx }) => { Search.propTypes = { id: PropTypes.string, - options: PropTypes.arrayOf( - PropTypes.shape({ - name: PropTypes.string.isRequired, - }) - ).isRequired, + options: PropTypes.array.isRequired, + filteredBy: PropTypes.string.isRequired, value: PropTypes.string.isRequired, handleChange: PropTypes.func.isRequired, sx: PropTypes.object, diff --git a/Client/src/Components/Search/index.css b/Client/src/Components/Search/index.css deleted file mode 100644 index e69de29bb..000000000 diff --git a/Client/src/Components/Search/index.jsx b/Client/src/Components/Search/index.jsx deleted file mode 100644 index 391b95c02..000000000 --- a/Client/src/Components/Search/index.jsx +++ /dev/null @@ -1,49 +0,0 @@ -import Autocomplete from '@mui/material/Autocomplete'; -import TextField from '@mui/material/TextField'; -import Chip from '@mui/material/Chip'; -import Box from '@mui/material/Box'; -import { useTheme } from "@mui/material"; - -const teamMembers = [ - { title: 'John Doe'}, - { title: 'Jane Smith'}, - { title: 'Alex Johnson'}, -]; - -/** - * @component - * @returns {JSX.Element} - */ - -export default function Search() - { - const theme = useTheme(); - return ( - {/* Add padding to the container */} - option.title} - filterSelectedOptions - renderInput={(params) => ( - - )} - renderTags={(value, getTagProps) => - value.map((option) => ( - - )) - } - /> - - ); -} diff --git a/Client/src/Pages/Monitors/Home/index.jsx b/Client/src/Pages/Monitors/Home/index.jsx index 36921d1f5..d51c3de2a 100644 --- a/Client/src/Pages/Monitors/Home/index.jsx +++ b/Client/src/Pages/Monitors/Home/index.jsx @@ -120,6 +120,7 @@ const Monitors = ({ isAdmin }) => { From 07190f82d5ccacf66a4db49ee6004ebdf36f1e22 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Thu, 19 Sep 2024 11:07:38 +0800 Subject: [PATCH 07/98] Connect search component to monitor table --- Client/src/Components/Inputs/Search/index.jsx | 20 +++++++++++++++---- .../Monitors/Home/MonitorTable/index.jsx | 7 ++++--- Client/src/Pages/Monitors/Home/index.jsx | 6 ++++-- Client/src/Utils/debounce.jsx | 18 +++++++++++++++++ 4 files changed, 42 insertions(+), 9 deletions(-) create mode 100644 Client/src/Utils/debounce.jsx diff --git a/Client/src/Components/Inputs/Search/index.jsx b/Client/src/Components/Inputs/Search/index.jsx index b69b25731..f4d931fd1 100644 --- a/Client/src/Components/Inputs/Search/index.jsx +++ b/Client/src/Components/Inputs/Search/index.jsx @@ -15,15 +15,26 @@ import SearchIcon from "../../../assets/icons/search.svg?react"; * @param {Object} props.sx - Additional styles to apply to the component * @returns {JSX.Element} The rendered Search component */ -const Search = ({ id, options, filteredBy, value, handleChange, sx }) => { +const Search = ({ + id, + options, + filteredBy, + value, + handleInputChange, + handleChange, + sx, +}) => { const theme = useTheme(); return ( { - handleChange(newValue); + onInputChange={(_, newValue) => { + handleInputChange(newValue); + }} + onChange={(_, newValue) => { + handleChange && handleChange(newValue); }} fullWidth freeSolo @@ -131,7 +142,8 @@ Search.propTypes = { options: PropTypes.array.isRequired, filteredBy: PropTypes.string.isRequired, value: PropTypes.string.isRequired, - handleChange: PropTypes.func.isRequired, + handleInputChange: PropTypes.func.isRequired, + handleChange: PropTypes.func, sx: PropTypes.object, }; diff --git a/Client/src/Pages/Monitors/Home/MonitorTable/index.jsx b/Client/src/Pages/Monitors/Home/MonitorTable/index.jsx index 732351be0..b7e50a499 100644 --- a/Client/src/Pages/Monitors/Home/MonitorTable/index.jsx +++ b/Client/src/Pages/Monitors/Home/MonitorTable/index.jsx @@ -108,7 +108,7 @@ TablePaginationActions.propTypes = { onPageChange: PropTypes.func.isRequired, }; -const MonitorTable = ({ isAdmin }) => { +const MonitorTable = ({ isAdmin, filter }) => { const theme = useTheme(); const navigate = useNavigate(); const dispatch = useDispatch(); @@ -155,7 +155,7 @@ const MonitorTable = ({ isAdmin }) => { normalize: true, page: page, rowsPerPage: rowsPerPage, - filter: null, + filter: filter, field: sort.field, order: sort.order, }); @@ -166,7 +166,7 @@ const MonitorTable = ({ isAdmin }) => { } }; fetchPage(); - }, [updateTrigger, authState, page, rowsPerPage]); + }, [updateTrigger, authState, page, rowsPerPage, filter, sort]); /** * Helper function to calculate the range of displayed rows. @@ -406,6 +406,7 @@ const MonitorTable = ({ isAdmin }) => { MonitorTable.propTypes = { isAdmin: PropTypes.bool, + filter: PropTypes.string, }; const MemoizedMonitorTable = memo(MonitorTable); diff --git a/Client/src/Pages/Monitors/Home/index.jsx b/Client/src/Pages/Monitors/Home/index.jsx index d51c3de2a..9db0cbf9a 100644 --- a/Client/src/Pages/Monitors/Home/index.jsx +++ b/Client/src/Pages/Monitors/Home/index.jsx @@ -13,6 +13,7 @@ import Breadcrumbs from "../../../Components/Breadcrumbs"; import Greeting from "../../../Utils/greeting"; import MonitorTable from "./MonitorTable"; import Search from "../../../Components/Inputs/Search"; +import useDebounce from "../../../Utils/debounce"; const Monitors = ({ isAdmin }) => { const theme = useTheme(); @@ -21,6 +22,7 @@ const Monitors = ({ isAdmin }) => { const authState = useSelector((state) => state.auth); const [search, setSearch] = useState(""); const dispatch = useDispatch({}); + const debouncedFilter = useDebounce(search, 500); useEffect(() => { dispatch(getUptimeMonitorsByTeamId(authState.authToken)); @@ -122,11 +124,11 @@ const Monitors = ({ isAdmin }) => { options={monitorState?.monitorsSummary.monitors} filteredBy="name" value={search} - handleChange={setSearch} + handleInputChange={setSearch} /> - + )} diff --git a/Client/src/Utils/debounce.jsx b/Client/src/Utils/debounce.jsx new file mode 100644 index 000000000..a89f8c687 --- /dev/null +++ b/Client/src/Utils/debounce.jsx @@ -0,0 +1,18 @@ +import { useState, useEffect } from "react"; + +const useDebounce = (value, delay) => { + const [debouncedValue, setDebouncedValue] = useState(value); + + useEffect(() => { + const handler = setTimeout(() => { + setDebouncedValue(value); + }, delay); + + return () => { + clearTimeout(handler); + }; + }, [value, delay]); + return debouncedValue; +}; + +export default useDebounce; From 59adc526fee267be5c6bb9fbf7d3a8aa24c5353e Mon Sep 17 00:00:00 2001 From: Daniel Cojocea Date: Thu, 19 Sep 2024 00:31:46 -0400 Subject: [PATCH 08/98] Added loading indicator to monitor table on search --- .../Monitors/Home/MonitorTable/index.jsx | 3 +- Client/src/Pages/Monitors/Home/index.jsx | 55 ++++++++++++++++++- 2 files changed, 54 insertions(+), 4 deletions(-) diff --git a/Client/src/Pages/Monitors/Home/MonitorTable/index.jsx b/Client/src/Pages/Monitors/Home/MonitorTable/index.jsx index b7e50a499..ff8297848 100644 --- a/Client/src/Pages/Monitors/Home/MonitorTable/index.jsx +++ b/Client/src/Pages/Monitors/Home/MonitorTable/index.jsx @@ -108,7 +108,7 @@ TablePaginationActions.propTypes = { onPageChange: PropTypes.func.isRequired, }; -const MonitorTable = ({ isAdmin, filter }) => { +const MonitorTable = ({ isAdmin, filter, setLoading }) => { const theme = useTheme(); const navigate = useNavigate(); const dispatch = useDispatch(); @@ -161,6 +161,7 @@ const MonitorTable = ({ isAdmin, filter }) => { }); setMonitors(res?.data?.data?.monitors ?? []); setMonitorCount(res?.data?.data?.monitorCount ?? 0); + setLoading(false); } catch (error) { logger.error(error); } diff --git a/Client/src/Pages/Monitors/Home/index.jsx b/Client/src/Pages/Monitors/Home/index.jsx index 9db0cbf9a..af439650b 100644 --- a/Client/src/Pages/Monitors/Home/index.jsx +++ b/Client/src/Pages/Monitors/Home/index.jsx @@ -4,7 +4,13 @@ import { useSelector, useDispatch } from "react-redux"; import { getUptimeMonitorsByTeamId } from "../../../Features/UptimeMonitors/uptimeMonitorsSlice"; import { useNavigate } from "react-router-dom"; import { useTheme } from "@emotion/react"; -import { Box, Button, Stack, Typography } from "@mui/material"; +import { + Box, + Button, + CircularProgress, + Stack, + Typography, +} from "@mui/material"; import PropTypes from "prop-types"; import SkeletonLayout from "./skeleton"; import Fallback from "./fallback"; @@ -21,12 +27,19 @@ const Monitors = ({ isAdmin }) => { const monitorState = useSelector((state) => state.uptimeMonitors); const authState = useSelector((state) => state.auth); const [search, setSearch] = useState(""); + const [isSearching, setIsSearching] = useState(""); const dispatch = useDispatch({}); const debouncedFilter = useDebounce(search, 500); + const handleSearch = (value) => { + setIsSearching(true); + setSearch(value); + }; + useEffect(() => { dispatch(getUptimeMonitorsByTeamId(authState.authToken)); }, [authState.authToken, dispatch]); + let loading = monitorState?.isLoading && monitorState?.monitorsSummary?.monitors?.length === 0; @@ -124,11 +137,47 @@ const Monitors = ({ isAdmin }) => { options={monitorState?.monitorsSummary.monitors} filteredBy="name" value={search} - handleInputChange={setSearch} + handleInputChange={handleSearch} /> - + + {isSearching && ( + <> + + + + + + )} + + )} From 21385864fc722fa4e66f8f606253eb5eda5c2def Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Thu, 19 Sep 2024 14:15:16 +0800 Subject: [PATCH 09/98] fix state initialization, add proptype --- Client/src/Pages/Monitors/Home/MonitorTable/index.jsx | 3 ++- Client/src/Pages/Monitors/Home/index.jsx | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/Client/src/Pages/Monitors/Home/MonitorTable/index.jsx b/Client/src/Pages/Monitors/Home/MonitorTable/index.jsx index ff8297848..8533ddacc 100644 --- a/Client/src/Pages/Monitors/Home/MonitorTable/index.jsx +++ b/Client/src/Pages/Monitors/Home/MonitorTable/index.jsx @@ -167,7 +167,7 @@ const MonitorTable = ({ isAdmin, filter, setLoading }) => { } }; fetchPage(); - }, [updateTrigger, authState, page, rowsPerPage, filter, sort]); + }, [updateTrigger, authState, page, rowsPerPage, filter, sort, setLoading]); /** * Helper function to calculate the range of displayed rows. @@ -408,6 +408,7 @@ const MonitorTable = ({ isAdmin, filter, setLoading }) => { MonitorTable.propTypes = { isAdmin: PropTypes.bool, filter: PropTypes.string, + setLoading: PropTypes.func, }; const MemoizedMonitorTable = memo(MonitorTable); diff --git a/Client/src/Pages/Monitors/Home/index.jsx b/Client/src/Pages/Monitors/Home/index.jsx index af439650b..c2a532bb9 100644 --- a/Client/src/Pages/Monitors/Home/index.jsx +++ b/Client/src/Pages/Monitors/Home/index.jsx @@ -27,7 +27,7 @@ const Monitors = ({ isAdmin }) => { const monitorState = useSelector((state) => state.uptimeMonitors); const authState = useSelector((state) => state.auth); const [search, setSearch] = useState(""); - const [isSearching, setIsSearching] = useState(""); + const [isSearching, setIsSearching] = useState(false); const dispatch = useDispatch({}); const debouncedFilter = useDebounce(search, 500); From dfa2d43a01abbc11f5d5b7a9ae6293c005f2eb95 Mon Sep 17 00:00:00 2001 From: "Gorkem Cetin (BWL)" <167266851+gorkem-bwl@users.noreply.github.com> Date: Thu, 19 Sep 2024 07:41:42 -0400 Subject: [PATCH 10/98] Add demo server URL, username and password --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 92ee37e35..b6bd7a590 100644 --- a/README.md +++ b/README.md @@ -15,6 +15,10 @@ BlueWave Uptime is an open source server monitoring application used to track the operational status and performance of servers and websites. It regularly checks whether a server/website is accessible and performs optimally, providing real-time alerts and reports on the monitored services' availability, downtime, and response time. +## Demo + +See [BlueWave Uptime](https://uptime-demo.bluewavelabs.ca/) in action. The username is uptimedemo@demo.com and the password is Demouser1! + ## Features - [x] Completely open source, deployable on your servers From 37f5e0024c2333b796e917c1084d6f2c26da31b8 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Thu, 19 Sep 2024 22:16:15 +0800 Subject: [PATCH 11/98] Remove maintenance from sidebar and comment out routes --- Client/src/App.jsx | 8 ++++---- Client/src/Components/Sidebar/index.jsx | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Client/src/App.jsx b/Client/src/App.jsx index d6fca146f..09fcfcf5f 100644 --- a/Client/src/App.jsx +++ b/Client/src/App.jsx @@ -83,14 +83,14 @@ function App() { path="integrations" element={} /> - } - /> - */} + {/* } - /> + /> */} } diff --git a/Client/src/Components/Sidebar/index.jsx b/Client/src/Components/Sidebar/index.jsx index 145b6f02e..1333b6f67 100644 --- a/Client/src/Components/Sidebar/index.jsx +++ b/Client/src/Components/Sidebar/index.jsx @@ -55,7 +55,7 @@ const menu = [ }, { name: "Incidents", path: "incidents", icon: }, // { name: "Status pages", path: "status", icon: }, - { name: "Maintenance", path: "maintenance", icon: }, + // { name: "Maintenance", path: "maintenance", icon: }, // { name: "Integrations", path: "integrations", icon: }, { name: "Account", From 1c8376dc24ca59cfd5d62ed808660a79c67cf6d6 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Sun, 22 Sep 2024 11:38:42 +0800 Subject: [PATCH 12/98] Refactor network service to use config objects for clarity --- .../TabPanels/Account/TeamPanel.jsx | 14 +- Client/src/Features/Auth/authSlice.js | 19 +- .../PageSpeedMonitor/pageSpeedMonitorSlice.js | 40 +- .../UptimeMonitors/uptimeMonitorsSlice.js | 53 ++- .../Pages/Incidents/IncidentTable/index.jsx | 40 +- .../Details/PaginationTable/index.jsx | 20 +- Client/src/Pages/Monitors/Details/index.jsx | 26 +- Client/src/Pages/PageSpeed/Details/index.jsx | 18 +- Client/src/Pages/Settings/index.jsx | 5 +- Client/src/Utils/NetworkService.js | 370 +++++++++--------- Server/routes/inviteRoute.js | 6 +- 11 files changed, 325 insertions(+), 286 deletions(-) diff --git a/Client/src/Components/TabPanels/Account/TeamPanel.jsx b/Client/src/Components/TabPanels/Account/TeamPanel.jsx index 07d209fc1..ac55cd5b1 100644 --- a/Client/src/Components/TabPanels/Account/TeamPanel.jsx +++ b/Client/src/Components/TabPanels/Account/TeamPanel.jsx @@ -55,7 +55,9 @@ const TeamPanel = () => { useEffect(() => { const fetchTeam = async () => { try { - const response = await networkService.getAllUsers(authToken); + const response = await networkService.getAllUsers({ + authToken: authToken, + }); setMembers(response.data.data); } catch (error) { createToast({ @@ -187,11 +189,11 @@ const TeamPanel = () => { } try { - await networkService.requestInvitationToken( - authToken, - toInvite.email, - toInvite.role - ); + await networkService.requestInvitationToken({ + authToken: authToken, + email: toInvite.email, + role: toInvite.role, + }); closeInviteModal(); createToast({ body: "Member invited. They will receive an email with details on how to create their account.", diff --git a/Client/src/Features/Auth/authSlice.js b/Client/src/Features/Auth/authSlice.js index f6d40c38a..7c8588b52 100644 --- a/Client/src/Features/Auth/authSlice.js +++ b/Client/src/Features/Auth/authSlice.js @@ -66,8 +66,11 @@ export const update = createAsyncThunk( form.deleteProfileImage && fd.append("deleteProfileImage", form.deleteProfileImage); - const res = await networkService.updateUser(token, user._id, fd); - console.log(res); + const res = await networkService.updateUser({ + authToken: token, + userId: user._id, + form: fd, + }); return res.data; } catch (error) { if (error.response && error.response.data) { @@ -88,7 +91,10 @@ export const deleteUser = createAsyncThunk( const user = jwtDecode(data); try { - const res = await networkService.deleteUser(data, user._id); + const res = await networkService.deleteUser({ + authToken: data, + userId: user._id, + }); return res.data; } catch (error) { if (error.response && error.response.data) { @@ -127,8 +133,11 @@ export const setNewPassword = createAsyncThunk( async (data, thunkApi) => { const { token, form } = data; try { - await networkService.validateRecoveryToken(token); - const res = await networkService.setNewPassword(token, form); + await networkService.validateRecoveryToken({ recoveryToken: token }); + const res = await networkService.setNewPassword({ + recoveryToken: token, + form: form, + }); return res.data; } catch (error) { if (error.response.data) { diff --git a/Client/src/Features/PageSpeedMonitor/pageSpeedMonitorSlice.js b/Client/src/Features/PageSpeedMonitor/pageSpeedMonitorSlice.js index 2e107e7e7..87e758bf3 100644 --- a/Client/src/Features/PageSpeedMonitor/pageSpeedMonitorSlice.js +++ b/Client/src/Features/PageSpeedMonitor/pageSpeedMonitorSlice.js @@ -13,7 +13,10 @@ export const createPageSpeed = createAsyncThunk( async (data, thunkApi) => { try { const { authToken, monitor } = data; - const res = await networkService.createMonitor(authToken, monitor); + const res = await networkService.createMonitor({ + authToken: authToken, + moniotr: monitor, + }); return res.data; } catch (error) { if (error.response && error.response.data) { @@ -33,7 +36,7 @@ export const getPagespeedMonitorById = createAsyncThunk( async (data, thunkApi) => { try { const { authToken, monitorId } = data; - const res = await networkService.getMonitorByid(authToken, monitorId); + const res = await networkService.getMonitorByid({ authToken, monitorId }); return res.data; } catch (error) { if (error.response && error.response.data) { @@ -53,11 +56,11 @@ export const getPageSpeedByTeamId = createAsyncThunk( async (token, thunkApi) => { const user = jwtDecode(token); try { - const res = await networkService.getMonitorsAndSummaryByTeamId( - token, - user.teamId, - ["pagespeed"] - ); + const res = await networkService.getMonitorsAndSummaryByTeamId({ + authToken: token, + teamId: user.teamId, + types: ["pagespeed"], + }); return res.data; } catch (error) { @@ -84,11 +87,11 @@ export const updatePageSpeed = createAsyncThunk( interval: monitor.interval, // notifications: monitor.notifications, }; - const res = await networkService.updateMonitor( - authToken, - monitor._id, - updatedFields - ); + const res = await networkService.updateMonitor({ + authToken: authToken, + monitorId: monitor._id, + updatedFields: updatedFields, + }); return res.data; } catch (error) { if (error.response && error.response.data) { @@ -108,10 +111,10 @@ export const deletePageSpeed = createAsyncThunk( async (data, thunkApi) => { try { const { authToken, monitor } = data; - const res = await networkService.deleteMonitorById( - authToken, - monitor._id - ); + const res = await networkService.deleteMonitorById({ + authToken: authToken, + monitorId: monitor._id, + }); return res.data; } catch (error) { if (error.response && error.response.data) { @@ -130,7 +133,10 @@ export const pausePageSpeed = createAsyncThunk( async (data, thunkApi) => { try { const { authToken, monitorId } = data; - const res = await networkService.pauseMonitorById(authToken, monitorId); + const res = await networkService.pauseMonitorById({ + authToken: authToken, + monitorId: monitorId, + }); return res.data; } catch (error) { if (error.response && error.response.data) { diff --git a/Client/src/Features/UptimeMonitors/uptimeMonitorsSlice.js b/Client/src/Features/UptimeMonitors/uptimeMonitorsSlice.js index a8b1ea737..3d1b619b5 100644 --- a/Client/src/Features/UptimeMonitors/uptimeMonitorsSlice.js +++ b/Client/src/Features/UptimeMonitors/uptimeMonitorsSlice.js @@ -13,7 +13,10 @@ export const createUptimeMonitor = createAsyncThunk( async (data, thunkApi) => { try { const { authToken, monitor } = data; - const res = await networkService.createMonitor(authToken, monitor); + const res = await networkService.createMonitor({ + authToken: authToken, + monitor: monitor, + }); return res.data; } catch (error) { if (error.response && error.response.data) { @@ -33,7 +36,7 @@ export const getUptimeMonitorById = createAsyncThunk( async (data, thunkApi) => { try { const { authToken, monitorId } = data; - const res = await networkService.getMonitorByid(authToken, monitorId); + const res = await networkService.getMonitorByid({ authToken, monitorId }); return res.data; } catch (error) { if (error.response && error.response.data) { @@ -53,11 +56,11 @@ export const getUptimeMonitorsByTeamId = createAsyncThunk( async (token, thunkApi) => { const user = jwtDecode(token); try { - const res = await networkService.getMonitorsAndSummaryByTeamId( - token, - user.teamId, - ["http", "ping"] - ); + const res = await networkService.getMonitorsAndSummaryByTeamId({ + authToken: token, + teamId: user.teamId, + types: ["http", "ping"], + }); return res.data; } catch (error) { if (error.response && error.response.data) { @@ -83,11 +86,11 @@ export const updateUptimeMonitor = createAsyncThunk( interval: monitor.interval, notifications: monitor.notifications, }; - const res = await networkService.updateMonitor( - authToken, - monitor._id, - updatedFields - ); + const res = await networkService.updateMonitor({ + authToken: authToken, + monitorId: monitor._id, + updatedFields: updatedFields, + }); return res.data; } catch (error) { if (error.response && error.response.data) { @@ -107,10 +110,10 @@ export const deleteUptimeMonitor = createAsyncThunk( async (data, thunkApi) => { try { const { authToken, monitor } = data; - const res = await networkService.deleteMonitorById( - authToken, - monitor._id - ); + const res = await networkService.deleteMonitorById({ + authToken: authToken, + monitorId: monitor._id, + }); return res.data; } catch (error) { if (error.response && error.response.data) { @@ -130,7 +133,10 @@ export const pauseUptimeMonitor = createAsyncThunk( async (data, thunkApi) => { try { const { authToken, monitorId } = data; - const res = await networkService.pauseMonitorById(authToken, monitorId); + const res = await networkService.pauseMonitorById({ + authToken: authToken, + monitorId: monitorId, + }); return res.data; } catch (error) { if (error.response && error.response.data) { @@ -150,7 +156,10 @@ export const deleteMonitorChecksByTeamId = createAsyncThunk( async (data, thunkApi) => { try { const { authToken, teamId } = data; - const res = await networkService.deleteChecksByTeamId(authToken, teamId); + const res = await networkService.deleteChecksByTeamId({ + authToken: authToken, + teamId: teamId, + }); return res.data; } catch (error) { if (error.response && error.response.data) { @@ -169,7 +178,9 @@ export const addDemoMonitors = createAsyncThunk( async (data, thunkApi) => { try { const { authToken } = data; - const res = await networkService.addDemoMonitors(authToken); + const res = await networkService.addDemoMonitors({ + authToken: authToken, + }); return res.data; } catch (error) { if (error.response && error.response.data) { @@ -188,7 +199,9 @@ export const deleteAllMonitors = createAsyncThunk( async (data, thunkApi) => { try { const { authToken } = data; - const res = await networkService.deleteAllMonitors(authToken); + const res = await networkService.deleteAllMonitors({ + authToken: authToken, + }); return res.data; } catch (error) { if (error.response && error.response.data) { diff --git a/Client/src/Pages/Incidents/IncidentTable/index.jsx b/Client/src/Pages/Incidents/IncidentTable/index.jsx index 6ca18a1e9..f47ad0cf0 100644 --- a/Client/src/Pages/Incidents/IncidentTable/index.jsx +++ b/Client/src/Pages/Incidents/IncidentTable/index.jsx @@ -53,27 +53,27 @@ const IncidentTable = ({ monitors, selectedMonitor, filter }) => { try { let res; if (selectedMonitor === "0") { - res = await networkService.getChecksByTeam( - authToken, - user.teamId, - "desc", - null, - null, - filter, - paginationController.page, - paginationController.rowsPerPage - ); + res = await networkService.getChecksByTeam({ + authToken: authToken, + userId: user.teamId, + sortOrder: "desc", + limit: null, + dateRange: null, + filter: filter, + page: paginationController.page, + rowsPerPage: paginationController.rowsPerPage, + }); } else { - res = await networkService.getChecksByMonitor( - authToken, - selectedMonitor, - "desc", - null, - null, - filter, - paginationController.page, - paginationController.rowsPerPage - ); + res = await networkService.getChecksByMonitor({ + authToken: authToken, + monitorId: selectedMonitor, + sortOrder: "desc", + limit: null, + dateRange: null, + sitler: filter, + page: paginationController.page, + rowsPerPage: paginationController.rowsPerPage, + }); } setChecks(res.data.data.checks); setChecksCount(res.data.data.checksCount); diff --git a/Client/src/Pages/Monitors/Details/PaginationTable/index.jsx b/Client/src/Pages/Monitors/Details/PaginationTable/index.jsx index b438f104b..1f2a2a293 100644 --- a/Client/src/Pages/Monitors/Details/PaginationTable/index.jsx +++ b/Client/src/Pages/Monitors/Details/PaginationTable/index.jsx @@ -40,16 +40,16 @@ const PaginationTable = ({ monitorId, dateRange }) => { useEffect(() => { const fetchPage = async () => { try { - const res = await networkService.getChecksByMonitor( - authToken, - monitorId, - "desc", - null, - dateRange, - null, - paginationController.page, - paginationController.rowsPerPage - ); + const res = await networkService.getChecksByMonitor({ + authToken: authToken, + moniotrId: monitorId, + sortOrder: "desc", + limit: null, + dateRange: dateRange, + filter: null, + page: paginationController.page, + rowsPerPage: paginationController.rowsPerPage, + }); setChecks(res.data.data.checks); setChecksCount(res.data.data.checksCount); } catch (error) { diff --git a/Client/src/Pages/Monitors/Details/index.jsx b/Client/src/Pages/Monitors/Details/index.jsx index 50ae8f558..31029fb45 100644 --- a/Client/src/Pages/Monitors/Details/index.jsx +++ b/Client/src/Pages/Monitors/Details/index.jsx @@ -63,15 +63,15 @@ const DetailsPage = ({ isAdmin }) => { const fetchMonitor = useCallback(async () => { try { - const res = await networkService.getStatsByMonitorId( - authToken, - monitorId, - null, - null, - dateRange, - 50, - true - ); + const res = await networkService.getStatsByMonitorId({ + authToken: authToken, + monitorId: monitorId, + sortOrder: null, + limit: null, + dateRange: dateRange, + numToDisplay: 50, + normalize: true, + }); setMonitor(res?.data?.data ?? {}); } catch (error) { logger.error(error); @@ -89,10 +89,10 @@ const DetailsPage = ({ isAdmin }) => { return; } try { - const res = await networkService.getCertificateExpiry( - authToken, - monitorId - ); + const res = await networkService.getCertificateExpiry({ + authToken: authToken, + monitorId: monitorId, + }); if (res?.data?.data?.certificateDate) { let [month, day, year] = res.data.data.certificateDate.split("/"); diff --git a/Client/src/Pages/PageSpeed/Details/index.jsx b/Client/src/Pages/PageSpeed/Details/index.jsx index 48d8aa86a..8fc137223 100644 --- a/Client/src/Pages/PageSpeed/Details/index.jsx +++ b/Client/src/Pages/PageSpeed/Details/index.jsx @@ -44,15 +44,15 @@ const PageSpeedDetails = () => { useEffect(() => { const fetchMonitor = async () => { try { - const res = await networkService.getStatsByMonitorId( - authToken, - monitorId, - "desc", - 50, - "day", - null, - null - ); + const res = await networkService.getStatsByMonitorId({ + authToken: authToken, + monitorId: monitorId, + sortOrder: "desc", + limit: 50, + dateRange: "day", + numToDisplay: null, + normalize: null, + }); setMonitor(res?.data?.data ?? {}); setAudits(res?.data?.data?.checks?.[0]?.audits ?? []); } catch (error) { diff --git a/Client/src/Pages/Settings/index.jsx b/Client/src/Pages/Settings/index.jsx index ac25c480d..806f29e75 100644 --- a/Client/src/Pages/Settings/index.jsx +++ b/Client/src/Pages/Settings/index.jsx @@ -69,7 +69,10 @@ const Settings = ({ isAdmin }) => { const handleSave = async () => { try { setChecksIsLoading(true); - await networkService.updateChecksTTL(authToken, form.ttl); + await networkService.updateChecksTTL({ + authToken: authToken, + ttl: form.ttl, + }); const updatedUser = { ...user, checkTTL: form.ttl }; const action = await dispatch( update({ authToken, localData: updatedUser }) diff --git a/Client/src/Utils/NetworkService.js b/Client/src/Utils/NetworkService.js index 63323d5a8..e5fd68111 100644 --- a/Client/src/Utils/NetworkService.js +++ b/Client/src/Utils/NetworkService.js @@ -24,15 +24,16 @@ class NetworkService { * ************************************ * * @async - * @param {string} authToken - The authorization token to be used in the request header. - * @param {string} monitorId - The monitor ID to be sent in the param. + * @param {Object} config - The configuration object. + * @param {string} config.authToken - The authorization token to be used in the request header. + * @param {string} config.monitorId - The monitor ID to be sent in the param. * @returns {Promise} The response from the axios GET request. */ - async getMonitorByid(authToken, monitorId) { - return this.axiosInstance.get(`/monitors/${monitorId}`, { + async getMonitorByid(config) { + return this.axiosInstance.get(`/monitors/${config.monitorId}`, { headers: { - Authorization: `Bearer ${authToken}`, + Authorization: `Bearer ${config.authToken}`, "Content-Type": "application/json", }, }); @@ -45,32 +46,46 @@ class NetworkService { * ************************************ * * @async - * @param {string} authToken - The authorization token to be used in the request header. - * @param {Object} monitor - The monitor object to be sent in the request body. + * @param {Object} config - The configuration object. + * @param {string} config.authToken - The authorization token to be used in the request header. + * @param {Object} config.monitor - The monitor object to be sent in the request body. * @returns {Promise} The response from the axios POST request. */ - async createMonitor(authToken, monitor) { - return this.axiosInstance.post(`/monitors`, monitor, { + async createMonitor(config) { + return this.axiosInstance.post(`/monitors`, config.monitor, { headers: { - Authorization: `Bearer ${authToken}`, + Authorization: `Bearer ${config.authToken}`, "Content-Type": "application/json", }, }); } - async getMonitorsAndSummaryByTeamId(authToken, teamId, types) { + /** + * + * ************************************ + * Gets monitors and summary of stats by TeamID + * ************************************ + * + * @async + * @param {Object} config - The configuration object. + * @param {string} config.authToken - The authorization token to be used in the request header. + * @param {string} config.teamId - Team ID + * @param {Array} config.types - Array of monitor types + * @returns {Promise} The response from the axios POST request. + */ + async getMonitorsAndSummaryByTeamId(config) { const params = new URLSearchParams(); - if (types) { - types.forEach((type) => { + if (config.types) { + config.types.forEach((type) => { params.append("type", type); }); } return this.axiosInstance.get( - `/monitors/team/summary/${teamId}?${params.toString()}`, + `/monitors/team/summary/${config.teamId}?${params.toString()}`, { headers: { - Authorization: `Bearer ${authToken}`, + Authorization: `Bearer ${config.authToken}`, "Content-Type": "application/json", }, } @@ -148,61 +163,29 @@ class NetworkService { * ************************************ * * @async - * @param {string} authToken - The authorization token to be used in the request header. - * @param {string} monitorId - The ID of the monitor whose statistics are to be retrieved. - * @param {string} [sortOrder] - The order in which to sort the retrieved statistics. - * @param {number} [limit] - The maximum number of statistics to retrieve. - * @param {string} [dateRange] - The date range for which to retrieve statistics. - * @param {number} [numToDisplay] - The number of checks to display. - * @param {boolean} [normalize] - Whether to normalize the retrieved statistics. + * @param {Object} config - The configuration object. + * @param {string} config.authToken - The authorization token to be used in the request header. + * @param {string} config.monitorId - The ID of the monitor whose statistics are to be retrieved. + * @param {string} config.sortOrder - The order in which to sort the retrieved statistics. + * @param {number} config.limit - The maximum number of statistics to retrieve. + * @param {string} config.dateRange - The date range for which to retrieve statistics. + * @param {number} config.numToDisplay - The number of checks to display. + * @param {boolean} config.normalize - Whether to normalize the retrieved statistics. * @returns {Promise} The response from the axios GET request. */ - async getStatsByMonitorId( - authToken, - monitorId, - sortOrder, - limit, - dateRange, - numToDisplay, - normalize - ) { + async getStatsByMonitorId(config) { const params = new URLSearchParams(); - if (sortOrder) params.append("sortOrder", sortOrder); - if (limit) params.append("limit", limit); - if (dateRange) params.append("dateRange", dateRange); - if (numToDisplay) params.append("numToDisplay", numToDisplay); - if (normalize) params.append("normalize", normalize); + if (config.sortOrder) params.append("sortOrder", config.sortOrder); + if (config.limit) params.append("limit", config.limit); + if (config.dateRange) params.append("dateRange", config.dateRange); + if (config.numToDisplay) params.append("numToDisplay", config.numToDisplay); + if (config.normalize) params.append("normalize", config.normalize); return this.axiosInstance.get( - `/monitors/stats/${monitorId}?${params.toString()}`, + `/monitors/stats/${config.monitorId}?${params.toString()}`, { headers: { - Authorization: `Bearer ${authToken}`, - }, - } - ); - } - - /** - * ************************************ - * Gets aggregate stats by monitor ID - * ************************************ - * - * @async - * @param {string} authToken - The authorization token to be used in the request header. - * @param {string} monitorId - The ID of the monitor whose certificate expiry is to be retrieved. - * @returns {Promise} The response from the axios GET request. - * - */ - async getAggregateStatsById(authToken, monitorId, dateRange) { - const params = new URLSearchParams(); - if (dateRange) params.append("dateRange", dateRange); - - return this.axiosInstance.get( - `/monitors/aggregate/${monitorId}?${params.toString()}`, - { - headers: { - Authorization: `Bearer ${authToken}`, + Authorization: `Bearer ${config.authToken}`, }, } ); @@ -214,18 +197,23 @@ class NetworkService { * ************************************ * * @async - * @param {string} authToken - The authorization token to be used in the request header. - * @param {string} monitorId - The ID of the monitor to be updated. - * @param {Object} updatedFields - The fields to be updated for the monitor. + * @param {Object} config - The configuration object. + * @param {string} config.authToken - The authorization token to be used in the request header. + * @param {string} config.monitorId - The ID of the monitor to be updated. + * @param {Object} config.updatedFields - The fields to be updated for the monitor. * @returns {Promise} The response from the axios PUT request. */ - async updateMonitor(authToken, monitorId, updatedFields) { - return this.axiosInstance.put(`/monitors/${monitorId}`, updatedFields, { - headers: { - Authorization: `Bearer ${authToken}`, - "Content-Type": "application/json", - }, - }); + async updateMonitor(config) { + return this.axiosInstance.put( + `/monitors/${config.monitorId}`, + config.updatedFields, + { + headers: { + Authorization: `Bearer ${config.authToken}`, + "Content-Type": "application/json", + }, + } + ); } /** @@ -234,14 +222,15 @@ class NetworkService { * ************************************ * * @async - * @param {string} authToken - The authorization token to be used in the request header. - * @param {string} monitorId - The ID of the monitor to be deleted. + * @param {Object} config - The configuration object. + * @param {string} config.authToken - The authorization token to be used in the request header. + * @param {string} config.monitorId - The ID of the monitor to be deleted. * @returns {Promise} The response from the axios DELETE request. */ - async deleteMonitorById(authToken, monitorId) { - return this.axiosInstance.delete(`/monitors/${monitorId}`, { + async deleteMonitorById(config) { + return this.axiosInstance.delete(`/monitors/${config.monitorId}`, { headers: { - Authorization: `Bearer ${authToken}`, + Authorization: `Bearer ${config.authToken}`, "Content-Type": "application/json", }, }); @@ -253,14 +242,15 @@ class NetworkService { * ************************************ * * @async - * @param {string} authToken - The authorization token to be used in the request header. - * @param {string} monitorId - The ID of the monitor to be deleted. + * @param {Object} config - The configuration object. + * @param {string} config.authToken - The authorization token to be used in the request header. + * @param {string} config.monitorId - The ID of the monitor to be deleted. * @returns {Promise} The response from the axios DELETE request. */ - async deleteChecksByTeamId(authToken, teamId) { - return this.axiosInstance.delete(`/checks/team/${teamId}`, { + async deleteChecksByTeamId(config) { + return this.axiosInstance.delete(`/checks/team/${config.teamId}`, { headers: { - Authorization: `Bearer ${authToken}`, + Authorization: `Bearer ${config.authToken}`, "Content-Type": "application/json", }, }); @@ -271,17 +261,18 @@ class NetworkService { * ************************************ * * @async - * @param {string} authToken - The authorization token to be used in the request header. - * @param {string} monitorId - The ID of the monitor to be paused. + * @param {Object} config - The configuration object. + * @param {string} config.authToken - The authorization token to be used in the request header. + * @param {string} config.monitorId - The ID of the monitor to be paused. * @returns {Promise} The response from the axios POST request. */ - async pauseMonitorById(authToken, monitorId) { + async pauseMonitorById(config) { return this.axiosInstance.post( - `/monitors/pause/${monitorId}`, + `/monitors/pause/${config.monitorId}`, {}, { headers: { - Authorization: `Bearer ${authToken}`, + Authorization: `Bearer ${config.authToken}`, "Content-Type": "application/json", }, } @@ -294,16 +285,17 @@ class NetworkService { * ************************************ * * @async - * @param {string} authToken - The authorization token to be used in the request header. + * @param {Object} config - The configuration object. + * @param {string} config.authToken - The authorization token to be used in the request header. * @returns {Promise} The response from the axios POST request. */ - async addDemoMonitors(authToken) { + async addDemoMonitors(config) { return this.axiosInstance.post( `/monitors/demo`, {}, { headers: { - Authorization: `Bearer ${authToken}`, + Authorization: `Bearer ${config.authToken}`, "Content-Type": "application/json", }, } @@ -316,13 +308,14 @@ class NetworkService { * ************************************ * * @async - * @param {string} authToken - The authorization token to be used in the request header. + * @param {Object} config - The configuration object. + * @param {string} config.authToken - The authorization token to be used in the request header. * @returns {Promise} The response from the axios DELETE request. */ - async deleteAllMonitors(authToken) { + async deleteAllMonitors(config) { return this.axiosInstance.delete(`/monitors/`, { headers: { - Authorization: `Bearer ${authToken}`, + Authorization: `Bearer ${config.authToken}`, "Content-Type": "application/json", }, }); @@ -334,15 +327,16 @@ class NetworkService { * ************************************ * * @async - * @param {string} authToken - The authorization token to be used in the request header. - * @param {string} monitorId - The ID of the monitor whose certificate expiry is to be retrieved. + * @param {Object} config - The configuration object. + * @param {string} config.authToken - The authorization token to be used in the request header. + * @param {string} config.monitorId - The ID of the monitor whose certificate expiry is to be retrieved. * @returns {Promise} The response from the axios GET request. * */ - async getCertificateExpiry(authToken, monitorId) { - return this.axiosInstance.get(`/monitors/certificate/${monitorId}`, { + async getCertificateExpiry(config) { + return this.axiosInstance.get(`/monitors/certificate/${config.monitorId}`, { headers: { - Authorization: `Bearer ${authToken}`, + Authorization: `Bearer ${config.authToken}`, }, }); } @@ -380,23 +374,35 @@ class NetworkService { * ************************************ * * @async - * @param {string} authToken - The authorization token to be used in the request header. - * @param {string} userId - The ID of the user to be updated. - * @param {Object} form - The form data for the user to be updated. + * @param {Object} config - The configuration object. + * @param {string} config.authToken - The authorization token to be used in the request header. + * @param {string} config.userId - The ID of the user to be updated. + * @param {Object} config.form - The form data for the user to be updated. * @returns {Promise} The response from the axios PUT request. * */ - async updateUser(authToken, userId, form) { - return this.axiosInstance.put(`/auth/user/${userId}`, form, { + async updateUser(config) { + return this.axiosInstance.put(`/auth/user/${config.userId}`, config.form, { headers: { - Authorization: `Bearer ${authToken}`, + Authorization: `Bearer ${config.authToken}`, }, }); } - async deleteUser(authToken, userId) { - return this.axiosInstance.delete(`/auth/user/${userId}`, { - headers: { Authorization: `Bearer ${authToken}` }, + /** + * ************************************ + * Deletes a user + * ************************************ + * + * @async + * @param {Object} config - The configuration object. + * @param {string} config.authToken - The authorization token to be used in the request header. + * @param {string} config.userId - The ID of the user to be deleted. + * + **/ + async deleteUser(config) { + return this.axiosInstance.delete(`/auth/user/${config.userId}`, { + headers: { Authorization: `Bearer ${config.authToken}` }, }); } @@ -420,13 +426,14 @@ class NetworkService { * ************************************ * * @async - * @param {string} recoveryToken - The recovery token to be validated. + * @param {Object} config - The configuration object. + * @param {string} config.recoveryToken - The recovery token to be validated. * @returns {Promise} The response from the axios POST request. * */ - async validateRecoveryToken(recoveryToken) { + async validateRecoveryToken(config) { return this.axiosInstance.post("/auth/recovery/validate", { - recoveryToken, + recoveryToken: config.recoveryToken, }); } @@ -436,14 +443,16 @@ class NetworkService { * ************************************ * * @async - * @param {Object} form - The form data for the password recovery request. + * @param {Object} config - The configuration object. + * @param {string} config.recoveryToken - The token for recovery request. + * @param {Object} config.form - The form data for the password recovery request. * @returns {Promise} The response from the axios POST request. * */ - async setNewPassword(recoveryToken, form) { + async setNewPassword(config) { return this.axiosInstance.post("/auth/recovery/reset", { - ...form, - recoveryToken, + ...config.form, + recoveryToken: config.recoveryToken, }); } @@ -466,13 +475,14 @@ class NetworkService { * ************************************ * * @async - * @param {string} authToken - The authorization token to be used in the request header. + * @param {Object} config - The configuration object. + * @param {string} config.authToken - The authorization token to be used in the request header. * @returns {Promise} The response from the axios GET request. * */ - async getAllUsers(authToken) { + async getAllUsers(config) { return this.axiosInstance.get("/auth/users", { - headers: { Authorization: `Bearer ${authToken}` }, + headers: { Authorization: `Bearer ${config.authToken}` }, }); } @@ -482,18 +492,19 @@ class NetworkService { * ************************************ * * @async - * @param {string} authToken - The authorization token to be used in the request header. - * @param {string} email - The email of the user to be invited. - * @param {string} role - The role of the user to be invited. + * @param {Object} config - The configuration object. + * @param {string} config.authToken - The authorization token to be used in the request header. + * @param {string} config.email - The email of the user to be invited. + * @param {string} config.role - The role of the user to be invited. * @returns {Promise} The response from the axios POST request. * */ - async requestInvitationToken(authToken, email, role) { + async requestInvitationToken(config) { return this.axiosInstance.post( `/invite`, - { email, role }, + { email: config.email, role: config.role }, { - headers: { Authorization: `Bearer ${authToken}` }, + headers: { Authorization: `Bearer ${config.authToken}` }, } ); } @@ -520,39 +531,34 @@ class NetworkService { * ************************************ * * @async - * @param {string} authToken - The authorization token to be used in the request header. - * @param {string} monitorId - The ID of the monitor. - * @param {string} sortOrder - The order in which to sort the checks. - * @param {number} limit - The maximum number of checks to retrieve. - * @param {string} dateRange - The range of dates for which to retrieve checks. - * @param {string} filter - The filter to apply to the checks. - * @param {number} page - The page number to retrieve in a paginated list. - * @param {number} rowsPerPage - The number of rows per page in a paginated list. + * @param {Object} config - The configuration object. + * @param {string} config.authToken - The authorization token to be used in the request header. + * @param {string} config.monitorId - The ID of the monitor. + * @param {string} config.sortOrder - The order in which to sort the checks. + * @param {number} config.limit - The maximum number of checks to retrieve. + * @param {string} config.dateRange - The range of dates for which to retrieve checks. + * @param {string} config.filter - The filter to apply to the checks. + * @param {number} config.page - The page number to retrieve in a paginated list. + * @param {number} config.rowsPerPage - The number of rows per page in a paginated list. * @returns {Promise} The response from the axios GET request. * */ - async getChecksByMonitor( - authToken, - monitorId, - sortOrder, - limit, - dateRange, - filter, - page, - rowsPerPage - ) { + async getChecksByMonitor(config) { const params = new URLSearchParams(); - if (sortOrder) params.append("sortOrder", sortOrder); - if (limit) params.append("limit", limit); - if (dateRange) params.append("dateRange", dateRange); - if (filter) params.append("filter", filter); - if (page) params.append("page", page); - if (rowsPerPage) params.append("rowsPerPage", rowsPerPage); + if (config.sortOrder) params.append("sortOrder", config.sortOrder); + if (config.limit) params.append("limit", config.limit); + if (config.dateRange) params.append("dateRange", config.dateRange); + if (config.filter) params.append("filter", config.filter); + if (config.page) params.append("page", config.page); + if (config.rowsPerPage) params.append("rowsPerPage", config.rowsPerPage); - return this.axiosInstance.get(`/checks/${monitorId}?${params.toString()}`, { - headers: { Authorization: `Bearer ${authToken}` }, - }); + return this.axiosInstance.get( + `/checks/${config.monitorId}?${params.toString()}`, + { + headers: { Authorization: `Bearer ${config.authToken}` }, + } + ); } /** @@ -561,49 +567,53 @@ class NetworkService { * ************************************ * * @async - * @param {string} authToken - The authorization token to be used in the request header. - * @param {string} userId - The ID of the user. - * @param {string} sortOrder - The order in which to sort the checks. - * @param {number} limit - The maximum number of checks to retrieve. - * @param {string} dateRange - The range of dates for which to retrieve checks. - * @param {string} filter - The filter to apply to the checks. - * @param {number} page - The page number to retrieve in a paginated list. - * @param {number} rowsPerPage - The number of rows per page in a paginated list. + * @param {Object} config - The configuration object. + * @param {string} config.authToken - The authorization token to be used in the request header. + * @param {string} config.userId - The ID of the user. + * @param {string} config.sortOrder - The order in which to sort the checks. + * @param {number} config.limit - The maximum number of checks to retrieve. + * @param {string} config.dateRange - The range of dates for which to retrieve checks. + * @param {string} config.filter - The filter to apply to the checks. + * @param {number} config.page - The page number to retrieve in a paginated list. + * @param {number} config.rowsPerPage - The number of rows per page in a paginated list. * @returns {Promise} The response from the axios GET request. * */ - async getChecksByTeam( - authToken, - teamId, - sortOrder, - limit, - dateRange, - filter, - page, - rowsPerPage - ) { + async getChecksByTeam(config) { const params = new URLSearchParams(); - if (sortOrder) params.append("sortOrder", sortOrder); - if (limit) params.append("limit", limit); - if (dateRange) params.append("dateRange", dateRange); - if (filter) params.append("filter", filter); - if (page) params.append("page", page); - if (rowsPerPage) params.append("rowsPerPage", rowsPerPage); + if (config.sortOrder) params.append("sortOrder", config.sortOrder); + if (config.limit) params.append("limit", config.limit); + if (config.dateRange) params.append("dateRange", config.dateRange); + if (config.filter) params.append("filter", config.filter); + if (config.page) params.append("page", config.page); + if (config.rowsPerPage) params.append("rowsPerPage", config.rowsPerPage); return this.axiosInstance.get( - `/checks/team/${teamId}?${params.toString()}`, + `/checks/team/${config.teamId}?${params.toString()}`, { - headers: { Authorization: `Bearer ${authToken}` }, + headers: { Authorization: `Bearer ${config.authToken}` }, } ); } - async updateChecksTTL(authToken, ttl) { + /** + * ************************************ + * Get all checks for a given user + * ************************************ + * + * @async + * @param {Object} config - The configuration object. + * @param {string} config.authToken - The authorization token to be used in the request header. + * @param {number} config.ttl - TTL for checks + * @returns {Promise} The response from the axios GET request. + * + */ + async updateChecksTTL(config) { return this.axiosInstance.put( `/checks/ttl`, - { ttl }, + { ttl: config.ttl }, { headers: { - Authorization: `Bearer ${authToken}`, + Authorization: `Bearer ${config.authToken}`, "Content-Type": "application/json", }, } diff --git a/Server/routes/inviteRoute.js b/Server/routes/inviteRoute.js index 54e74b0fa..17744bf82 100644 --- a/Server/routes/inviteRoute.js +++ b/Server/routes/inviteRoute.js @@ -13,10 +13,6 @@ router.post( verifyJWT, inviteController ); -router.post( - "/verify", - isAllowed(["admin", "superadmin"]), - inviteVerifyController -); +router.post("/verify", inviteVerifyController); module.exports = router; From 0791c7e5c50b2bc62db4139663fff9ccc26cf2dc Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Sun, 22 Sep 2024 12:17:34 +0800 Subject: [PATCH 13/98] Fix typos --- .../src/Features/PageSpeedMonitor/pageSpeedMonitorSlice.js | 7 +++++-- Client/src/Features/UptimeMonitors/uptimeMonitorsSlice.js | 5 ++++- .../src/Pages/Monitors/Details/PaginationTable/index.jsx | 2 +- Client/src/Utils/NetworkService.js | 2 +- 4 files changed, 11 insertions(+), 5 deletions(-) diff --git a/Client/src/Features/PageSpeedMonitor/pageSpeedMonitorSlice.js b/Client/src/Features/PageSpeedMonitor/pageSpeedMonitorSlice.js index 87e758bf3..0322a5143 100644 --- a/Client/src/Features/PageSpeedMonitor/pageSpeedMonitorSlice.js +++ b/Client/src/Features/PageSpeedMonitor/pageSpeedMonitorSlice.js @@ -15,7 +15,7 @@ export const createPageSpeed = createAsyncThunk( const { authToken, monitor } = data; const res = await networkService.createMonitor({ authToken: authToken, - moniotr: monitor, + monitor: monitor, }); return res.data; } catch (error) { @@ -36,7 +36,10 @@ export const getPagespeedMonitorById = createAsyncThunk( async (data, thunkApi) => { try { const { authToken, monitorId } = data; - const res = await networkService.getMonitorByid({ authToken, monitorId }); + const res = await networkService.getMonitorById({ + authToken: authToken, + monitorId: monitorId, + }); return res.data; } catch (error) { if (error.response && error.response.data) { diff --git a/Client/src/Features/UptimeMonitors/uptimeMonitorsSlice.js b/Client/src/Features/UptimeMonitors/uptimeMonitorsSlice.js index 3d1b619b5..f6c3cb10a 100644 --- a/Client/src/Features/UptimeMonitors/uptimeMonitorsSlice.js +++ b/Client/src/Features/UptimeMonitors/uptimeMonitorsSlice.js @@ -36,7 +36,10 @@ export const getUptimeMonitorById = createAsyncThunk( async (data, thunkApi) => { try { const { authToken, monitorId } = data; - const res = await networkService.getMonitorByid({ authToken, monitorId }); + const res = await networkService.getMonitorById({ + authToken: authToken, + monitorId: monitorId, + }); return res.data; } catch (error) { if (error.response && error.response.data) { diff --git a/Client/src/Pages/Monitors/Details/PaginationTable/index.jsx b/Client/src/Pages/Monitors/Details/PaginationTable/index.jsx index 1f2a2a293..8538ac169 100644 --- a/Client/src/Pages/Monitors/Details/PaginationTable/index.jsx +++ b/Client/src/Pages/Monitors/Details/PaginationTable/index.jsx @@ -42,7 +42,7 @@ const PaginationTable = ({ monitorId, dateRange }) => { try { const res = await networkService.getChecksByMonitor({ authToken: authToken, - moniotrId: monitorId, + monitoirId: monitorId, sortOrder: "desc", limit: null, dateRange: dateRange, diff --git a/Client/src/Utils/NetworkService.js b/Client/src/Utils/NetworkService.js index e5fd68111..50a6a095a 100644 --- a/Client/src/Utils/NetworkService.js +++ b/Client/src/Utils/NetworkService.js @@ -30,7 +30,7 @@ class NetworkService { * @returns {Promise} The response from the axios GET request. */ - async getMonitorByid(config) { + async getMonitorById(config) { return this.axiosInstance.get(`/monitors/${config.monitorId}`, { headers: { Authorization: `Bearer ${config.authToken}`, From 41f59a2660da2874f445e19132401a7ad8449ff0 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Sun, 22 Sep 2024 12:19:08 +0800 Subject: [PATCH 14/98] fix js doc --- Client/src/Utils/NetworkService.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Client/src/Utils/NetworkService.js b/Client/src/Utils/NetworkService.js index 50a6a095a..c087fb73a 100644 --- a/Client/src/Utils/NetworkService.js +++ b/Client/src/Utils/NetworkService.js @@ -244,7 +244,7 @@ class NetworkService { * @async * @param {Object} config - The configuration object. * @param {string} config.authToken - The authorization token to be used in the request header. - * @param {string} config.monitorId - The ID of the monitor to be deleted. + * @param {string} config.teamId - The team ID of the monitors to be deleted. * @returns {Promise} The response from the axios DELETE request. */ async deleteChecksByTeamId(config) { From 61b0e6154de9a141faa22048f6027f2795d4b1fe Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Mon, 23 Sep 2024 10:25:26 +0800 Subject: [PATCH 15/98] Reset pagination on filter chagne --- .../Monitors/Home/MonitorTable/index.jsx | 75 ++++++++++++------- 1 file changed, 47 insertions(+), 28 deletions(-) diff --git a/Client/src/Pages/Monitors/Home/MonitorTable/index.jsx b/Client/src/Pages/Monitors/Home/MonitorTable/index.jsx index 8533ddacc..b86a739e0 100644 --- a/Client/src/Pages/Monitors/Home/MonitorTable/index.jsx +++ b/Client/src/Pages/Monitors/Home/MonitorTable/index.jsx @@ -17,7 +17,7 @@ import ArrowDownwardRoundedIcon from "@mui/icons-material/ArrowDownwardRounded"; import ArrowUpwardRoundedIcon from "@mui/icons-material/ArrowUpwardRounded"; import { setRowsPerPage } from "../../../../Features/UI/uiSlice"; -import { useState, useEffect, memo } from "react"; +import { useState, useEffect, memo, useCallback, useRef } from "react"; import { useNavigate } from "react-router"; import { logger } from "../../../../Utils/Logger"; import Host from "../host"; @@ -49,7 +49,6 @@ import useUtils from "../../utils"; */ const TablePaginationActions = (props) => { const { count, page, rowsPerPage, onPageChange } = props; - const handleFirstPageButtonClick = (event) => { onPageChange(event, 0); }; @@ -121,6 +120,7 @@ const MonitorTable = ({ isAdmin, filter, setLoading }) => { const authState = useSelector((state) => state.auth); const [updateTrigger, setUpdateTrigger] = useState(false); const [sort, setSort] = useState({}); + const prevFilter = useRef(filter); const handleActionMenuDelete = () => { setUpdateTrigger((prev) => !prev); @@ -140,34 +140,53 @@ const MonitorTable = ({ isAdmin, filter, setLoading }) => { setPage(0); }; + const fetchPage = useCallback(async () => { + try { + const { authToken } = authState; + const user = jwtDecode(authToken); + const res = await networkService.getMonitorsByTeamId({ + authToken, + teamId: user.teamId, + limit: 25, + types: ["http", "ping"], + status: null, + checkOrder: "desc", + normalize: true, + page: page, + rowsPerPage: rowsPerPage, + filter: filter, + field: sort.field, + order: sort.order, + }); + setMonitors(res?.data?.data?.monitors ?? []); + setMonitorCount(res?.data?.data?.monitorCount ?? 0); + setLoading(false); + } catch (error) { + logger.error(error); + } + }, [authState, page, rowsPerPage, filter, sort, setLoading]); + useEffect(() => { - const fetchPage = async () => { - try { - const { authToken } = authState; - const user = jwtDecode(authToken); - const res = await networkService.getMonitorsByTeamId({ - authToken, - teamId: user.teamId, - limit: 25, - types: ["http", "ping"], - status: null, - checkOrder: "desc", - normalize: true, - page: page, - rowsPerPage: rowsPerPage, - filter: filter, - field: sort.field, - order: sort.order, - }); - setMonitors(res?.data?.data?.monitors ?? []); - setMonitorCount(res?.data?.data?.monitorCount ?? 0); - setLoading(false); - } catch (error) { - logger.error(error); - } - }; fetchPage(); - }, [updateTrigger, authState, page, rowsPerPage, filter, sort, setLoading]); + }, [ + updateTrigger, + authState, + page, + rowsPerPage, + filter, + sort, + setLoading, + fetchPage, + ]); + + // Listen for changes in filter, if new value reset the page + useEffect(() => { + if (prevFilter.current !== filter) { + setPage(0); + fetchPage(); + } + prevFilter.current = filter; + }, [filter, fetchPage]); /** * Helper function to calculate the range of displayed rows. From 42e5cac7080cfdd64d16324875dccebe20865074 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Mon, 23 Sep 2024 13:10:34 +0800 Subject: [PATCH 16/98] Add quickstart docker compose file and script --- .gitignore | 3 ++- Docker/mongoDB.Dockerfile | 1 + Docker/quickstart/docker-compose.yaml | 34 +++++++++++++++++++++++++++ 3 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 Docker/quickstart/docker-compose.yaml diff --git a/.gitignore b/.gitignore index ebf2039ec..ebdafb70d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ .vite .vscode *.sh -!uptime.sh \ No newline at end of file +!uptime.sh +!quickstart.sh \ No newline at end of file diff --git a/Docker/mongoDB.Dockerfile b/Docker/mongoDB.Dockerfile index 969a320c2..19fc6e358 100644 --- a/Docker/mongoDB.Dockerfile +++ b/Docker/mongoDB.Dockerfile @@ -1,3 +1,4 @@ FROM mongo +COPY ./Docker/mongo/init/create_users.js /docker-entrypoint-initdb.d/ EXPOSE 27017 CMD ["mongod"] diff --git a/Docker/quickstart/docker-compose.yaml b/Docker/quickstart/docker-compose.yaml new file mode 100644 index 000000000..e2c6e0bae --- /dev/null +++ b/Docker/quickstart/docker-compose.yaml @@ -0,0 +1,34 @@ +services: + client: + image: bluewaveuptime/uptime_client:latest + ports: + - "80:80" + - "443:443" + depends_on: + - server + volumes: + - ./nginx/conf.d:/etc/nginx/conf.d/:ro + server: + image: bluewaveuptime/uptime_server:latest + ports: + - "5000:5000" + env_file: + - server.env + depends_on: + - redis + - mongodb + redis: + image: bluewaveuptime/uptime_redis:latest + ports: + - "6379:6379" + volumes: + - ./redis/data:/data + mongodb: + image: bluewaveuptime/uptime_database_mongo:latest + command: ["mongod", "--quiet", "--auth"] + ports: + - "27017:27017" + volumes: + - ./mongo/data:/data/db + env_file: + - mongo.env From beec977bcdf67f29f3f81c5e9a0ef208b0941357 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Mon, 23 Sep 2024 13:17:05 +0800 Subject: [PATCH 17/98] Update readme --- README.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/README.md b/README.md index b6bd7a590..743d26370 100644 --- a/README.md +++ b/README.md @@ -78,6 +78,7 @@ Also check other developer and contributor-friendly projects of BlueWave: - Clone this repository to your local machine +1. [Quickstart for Users](#user-quickstart) 1. [Quickstart for Developers](#dev-quickstart) 1. [Docker Compose](#docker-compose) 1. [Installation (Client)](#client) @@ -133,6 +134,15 @@ Also check other developer and contributor-friendly projects of BlueWave: --- +#### Quickstart for Users + +1. Download our [Docker Compose File]() +2. Download our [Quickstart script]() +3. Place these files in a directory of your choice +4. Run `quickstart.sh` and generate config files +5. Run `docker compose up` to start the application +6. Application is running at `http://localhost` + #### Quickstart for Developers MAKE SURE YOU CD TO THE SPECIFIED DIRECTORIES AS PATHS IN COMMANDS ARE RELATIVE From c6fc996b94d5bb1e4d0d86cfaa14e3fae838a848 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Mon, 23 Sep 2024 13:24:17 +0800 Subject: [PATCH 18/98] Add script to gitignore --- .gitignore | 3 +- Docker/.gitignore | 1 + Docker/quickstart/quickstart.sh | 123 ++++++++++++++++++++++++++++++++ 3 files changed, 125 insertions(+), 2 deletions(-) create mode 100755 Docker/quickstart/quickstart.sh diff --git a/.gitignore b/.gitignore index ebdafb70d..ebf2039ec 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,4 @@ .vite .vscode *.sh -!uptime.sh -!quickstart.sh \ No newline at end of file +!uptime.sh \ No newline at end of file diff --git a/Docker/.gitignore b/Docker/.gitignore index 89aa6bfac..3035bcf7a 100644 --- a/Docker/.gitignore +++ b/Docker/.gitignore @@ -1,4 +1,5 @@ *.sh +!quickstart.sh !build_images.sh mongo/data/* redis/data/* diff --git a/Docker/quickstart/quickstart.sh b/Docker/quickstart/quickstart.sh new file mode 100755 index 000000000..b460daaad --- /dev/null +++ b/Docker/quickstart/quickstart.sh @@ -0,0 +1,123 @@ +default_server_base_url="http://localhost:5000/api/v1" +default_client_host="http://localhost" +default_jwt_secret="my_secret" +default_db_type="MongoDB" +default_redis_host="redis" +default_redis_port=6379 +default_token_ttl="99d" + +default_db_username="uptime_user" +default_db_password="uptime_password" + +default_system_email_host="smtp.gmail.com" +default_system_email_port=465 + + +echo "Welcome to the Uptime Monitor Setup Script! \n" +echo + +echo "Configuring server" +printf '%*s\n' "${COLUMNS:-$(tput cols)}" '' | tr ' ' '*' +echo + +db_type=$default_db_type +redis_host=$default_redis_host +redis_port=$default_redis_port +jwt_secret=$default_jwt_secret + + +read -p "Enter a username for your database [$default_db_username]: " db_username +db_username="${db_username:-$default_db_username}" + +read -p "Enter a password for your database [$default_db_password]: " db_password +db_password="${db_password:-$default_db_password}" + +read -p "Enter your system email host [$default_system_email_host]: " system_email_host +system_email_host="${system_email_host:-$default_system_email_host}" +echo "System email host: $system_email_host" +echo + +read -p "Enter your DB connection string [$default_db_connection_string]: " db_connection_string +db_connection_string="mongodb://${db_username}:${db_password}@mongodb:27017/uptime_db" +echo "DB connection string: $db_connection_string" +echo + +read -p "Enter your system email port [$default_system_email_port]: " system_email_port +system_email_port="${system_email_port:-$default_system_email_port}" +echo "System email port: $system_email_port" +echo + + +read -p "Enter your system email address: " system_email_address +echo "System email address: $system_email_address" +echo + +read -p "Enter your system email password: " system_email_password +echo "System email password: $system_email_password" +echo + +read -p "Enter your Token TTL [$default_token_ttl]: " token_ttl +token_ttl="${token_ttl:-$default_token_ttl}" +echo "Token TTL: $token_ttl" +echo + +read -p "Enter your Pagespeed API key: " pagespeed_api_key +echo "Pagespeed API key: $pagespeed_api_key" +echo + +echo "Writing to ./server.env" +echo + +{ + echo "CLIENT_HOST=\"$client_host\"" + echo "JWT_SECRET=\"$jwt_secret\"" + echo "DB_TYPE=\"$db_type\"" + echo "DB_CONNECTION_STRING=\"$db_connection_string\"" + echo "REDIS_HOST=\"$redis_host\"" + echo "REDIS_PORT=$redis_port" + echo "SYSTEM_EMAIL_HOST=\"$system_email_host\"" + echo "SYSTEM_EMAIL_PORT=$system_email_port" + echo "SYSTEM_EMAIL_ADDRESS=\"$system_email_address\"" + echo "SYSTEM_EMAIL_PASSWORD=\"$system_email_password\"" + echo "TOKEN_TTL=\"$token_ttl\"" + echo "PAGESPEED_API_KEY=\"$pagespeed_api_key\"" +} > ./server.env + + +echo +{ + echo USERNAME_ENV_VAR=${db_username} + echo PASSWORD_ENV_VAR=${db_password} +} > ./mongo.env + +mkdir -p ./nginx/conf.d/ + + +cat < ./nginx/conf.d/default.conf +server { + listen 80; + listen [::]:80; + + server_name uptime-demo.bluewavelabs.ca; + server_tokens off; + + location /.well-known/acme-challenge/ { + root /var/www/certbot; + } + + location / { + root /usr/share/nginx/html; + index index.html index.htm; + try_files \$uri \$uri/ /index.html; + } + + location /api/ { + proxy_pass http://server:5000/api/; + proxy_http_version 1.1; + proxy_set_header Host \$host; + proxy_set_header X-Real-IP \$remote_addr; + proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto \$scheme; + } +} +EOL \ No newline at end of file From 8025a78b76530205651a3e7e00c2f057520914ee Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Mon, 23 Sep 2024 13:25:18 +0800 Subject: [PATCH 19/98] Add links to readme --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 743d26370..d7b07e72a 100644 --- a/README.md +++ b/README.md @@ -136,8 +136,8 @@ Also check other developer and contributor-friendly projects of BlueWave: #### Quickstart for Users -1. Download our [Docker Compose File]() -2. Download our [Quickstart script]() +1. Download our [Docker Compose File](Docker/quickstart/docker-compose.yaml) +2. Download our [Quickstart script](Docker/quickstart/quickstart.sh) 3. Place these files in a directory of your choice 4. Run `quickstart.sh` and generate config files 5. Run `docker compose up` to start the application From e3d14bba372c3a2ddf3e0cc381f16ff61204cda8 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Mon, 23 Sep 2024 13:26:42 +0800 Subject: [PATCH 20/98] add leading / to links --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index d7b07e72a..3c96a0af4 100644 --- a/README.md +++ b/README.md @@ -136,8 +136,8 @@ Also check other developer and contributor-friendly projects of BlueWave: #### Quickstart for Users -1. Download our [Docker Compose File](Docker/quickstart/docker-compose.yaml) -2. Download our [Quickstart script](Docker/quickstart/quickstart.sh) +1. Download our [Docker Compose File](/Docker/quickstart/docker-compose.yaml) +2. Download our [Quickstart script](/Docker/quickstart/quickstart.sh) 3. Place these files in a directory of your choice 4. Run `quickstart.sh` and generate config files 5. Run `docker compose up` to start the application From e8183cc4f32d7f5d67821d31c49ef16305606de6 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Tue, 24 Sep 2024 13:34:56 +0800 Subject: [PATCH 21/98] Fixed hardcoded array access --- Client/src/Components/Sidebar/index.jsx | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Client/src/Components/Sidebar/index.jsx b/Client/src/Components/Sidebar/index.jsx index 1333b6f67..aa80e0c85 100644 --- a/Client/src/Components/Sidebar/index.jsx +++ b/Client/src/Components/Sidebar/index.jsx @@ -93,8 +93,9 @@ function Sidebar() { const { user } = useSelector((state) => state.auth); // Remove demo password if demo - if (user.role?.includes("demo")) { - menu[3].nested = menu[3].nested.filter((item) => { + const accountMenuItem = menu.find((item) => item.name === "account"); + if (user.role?.includes("demo") && accountMenuItem) { + accountMenuItem.nested = accountMenuItem.nested.filter((item) => { return item.name !== "Password"; }); } From 47f2f4fcb1fd99d93f5dc7d76b42d6ba257644a9 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Tue, 24 Sep 2024 13:49:44 +0800 Subject: [PATCH 22/98] userId -> teamId --- Client/src/Pages/Incidents/IncidentTable/index.jsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Client/src/Pages/Incidents/IncidentTable/index.jsx b/Client/src/Pages/Incidents/IncidentTable/index.jsx index f47ad0cf0..ef8356031 100644 --- a/Client/src/Pages/Incidents/IncidentTable/index.jsx +++ b/Client/src/Pages/Incidents/IncidentTable/index.jsx @@ -55,7 +55,7 @@ const IncidentTable = ({ monitors, selectedMonitor, filter }) => { if (selectedMonitor === "0") { res = await networkService.getChecksByTeam({ authToken: authToken, - userId: user.teamId, + teamId: user.teamId, sortOrder: "desc", limit: null, dateRange: null, From d2ab33492a08d9e90e66d89f07a0539cc5b2fe43 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Tue, 24 Sep 2024 13:56:58 +0800 Subject: [PATCH 23/98] Update auth endpoints --- Server/controllers/authController.js | 17 --- Server/index.js | 12 ++- Server/openapi.json | 156 ++++++++++++++++----------- 3 files changed, 104 insertions(+), 81 deletions(-) diff --git a/Server/controllers/authController.js b/Server/controllers/authController.js index a3e245ef3..f39ffb019 100644 --- a/Server/controllers/authController.js +++ b/Server/controllers/authController.js @@ -49,23 +49,6 @@ const registerController = async (req, res, next) => { next(error); return; } - - // TODO Can there be more than one admin? - // // Check if an admin user exists, if so, error - // try { - // const admin = await req.db.checkAdmin(req, res); - // console.log(admin); - // if (admin === true) { - // throw new Error(errorMessages.AUTH_ADMIN_EXISTS); - // } - // } catch (error) { - // console.log("WEEEEEEE", error.message); - // error.service = SERVICE_NAME; - // error.status = 403; - // next(error); - // return; - // } - // Create a new user try { const newUser = await req.db.insertUser({ ...req.body }, req.file); diff --git a/Server/index.js b/Server/index.js index 846b11e3d..672aa4882 100644 --- a/Server/index.js +++ b/Server/index.js @@ -1,3 +1,7 @@ +const path = require("path"); +const fs = require("fs"); +const swaggerUi = require("swagger-ui-express"); + const express = require("express"); const helmet = require("helmet"); const cors = require("cors"); @@ -21,8 +25,11 @@ const NetworkService = require("./service/networkService"); const EmailService = require("./service/emailService"); const PageSpeedService = require("./service/pageSpeedService"); const SERVICE_NAME = "Server"; -let cleaningUp = false; +let cleaningUp = false; +const openApiSpec = JSON.parse( + fs.readFileSync(path.join(__dirname, "openapi.json"), "utf8") +); // Need to wrap server setup in a function to handle async nature of JobQueue const startApp = async () => { // ************************** @@ -70,6 +77,9 @@ const startApp = async () => { next(); }); + // Swagger UI + app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(openApiSpec)); + //routes app.use("/api/v1/auth", authRouter); app.use("/api/v1/invite", inviteRouter); diff --git a/Server/openapi.json b/Server/openapi.json index 23c16521d..1f7294be3 100644 --- a/Server/openapi.json +++ b/Server/openapi.json @@ -81,7 +81,14 @@ "application/json": { "schema": { "type": "object", - "required": ["firstName", "lastName", "email", "password", "role", "teamId"], + "required": [ + "firstName", + "lastName", + "email", + "password", + "role", + "teamId" + ], "properties": { "firstName": { "type": "string" @@ -103,7 +110,7 @@ }, "role": { "type": "array", - "enum": [["user"], ["admin"], ["superadmin"]], + "enum": [["user"], ["admin"], ["superadmin"], ["Demo"]], "default": ["superadmin"] }, "teamId": { @@ -207,78 +214,54 @@ } } }, - "/auth/user/:userId": { + "/auth/user/{userId}": { "put": { "tags": ["auth"], - "description": "Change user informations", - "responses": { - "200": { - "description": "OK", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UserSuccessResponse" - } - } + "description": "Change user information", + "parameters": [ + { + "name": "userId", + "in": "path", + "required": true, + "schema": { + "type": "string" } - }, - "422": { - "description": "Unprocessable Content", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ErrorResponse" - } - } - } - }, - "500": { - "description": "Internal Server Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ErrorResponse" - } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UserUpdateRequest" } } } - } + }, + "security": [ + { + "bearerAuth": [] + } + ] }, "delete": { "tags": ["auth"], "description": "Delete user", - "responses": { - "200": { - "description": "OK", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UserSuccessResponse" - } - } - } - }, - "422": { - "description": "Unprocessable Content", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ErrorResponse" - } - } - } - }, - "500": { - "description": "Internal Server Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ErrorResponse" - } - } + "parameters": [ + { + "name": "userId", + "in": "path", + "required": true, + "schema": { + "type": "string" } } - } + ], + "security": [ + { + "bearerAuth": [] + } + ] } }, "/auth/users/admin": { @@ -587,12 +570,20 @@ } }, "components": { + "securitySchemes": { + "bearerAuth": { + "type": "http", + "scheme": "bearer", + "bearerFormat": "JWT" + } + }, "schemas": { "ErrorResponse": { "type": "object", "properties": { "success": { - "type": "boolean" + "type": "boolean", + "default": false }, "msg": { "type": "string" @@ -613,6 +604,45 @@ } } }, + "UserUpdateRequest": { + "type": "object", + "required": [ + "firstName", + "lastName", + "email", + "password", + "role", + "teamId" + ], + "properties": { + "firstName": { + "type": "string" + }, + "lastName": { + "type": "string" + }, + "password": { + "type": "string", + "format": "password" + }, + "newPassword": { + "type": "string", + "format": "password" + }, + "profileImage": { + "type": "file", + "format": "file" + }, + "role": { + "type": "array", + "enum": [["user"], ["admin"], ["superadmin"], ["Demo"]], + "default": ["superadmin"] + }, + "deleteProfileImage": { + "type": "boolean" + } + } + }, "UserSuccessResponse": { "type": "object", "properties": { From 7398ce219faeca47851e4fe6e602da7c7166f39b Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Tue, 24 Sep 2024 13:58:39 +0800 Subject: [PATCH 24/98] Fix typo in monitor details page --- Client/src/Pages/Monitors/Details/PaginationTable/index.jsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Client/src/Pages/Monitors/Details/PaginationTable/index.jsx b/Client/src/Pages/Monitors/Details/PaginationTable/index.jsx index 8538ac169..009ec0b71 100644 --- a/Client/src/Pages/Monitors/Details/PaginationTable/index.jsx +++ b/Client/src/Pages/Monitors/Details/PaginationTable/index.jsx @@ -42,7 +42,7 @@ const PaginationTable = ({ monitorId, dateRange }) => { try { const res = await networkService.getChecksByMonitor({ authToken: authToken, - monitoirId: monitorId, + monitorId: monitorId, sortOrder: "desc", limit: null, dateRange: dateRange, From 5843192bdeb2c63bed59d87e7ab2048d5cc68bfd Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Tue, 24 Sep 2024 14:11:19 +0800 Subject: [PATCH 25/98] -> --- Client/src/Components/Sidebar/index.jsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Client/src/Components/Sidebar/index.jsx b/Client/src/Components/Sidebar/index.jsx index aa80e0c85..591a93a2b 100644 --- a/Client/src/Components/Sidebar/index.jsx +++ b/Client/src/Components/Sidebar/index.jsx @@ -93,7 +93,7 @@ function Sidebar() { const { user } = useSelector((state) => state.auth); // Remove demo password if demo - const accountMenuItem = menu.find((item) => item.name === "account"); + const accountMenuItem = menu.find((item) => item.name === "Account"); if (user.role?.includes("demo") && accountMenuItem) { accountMenuItem.nested = accountMenuItem.nested.filter((item) => { return item.name !== "Password"; From 7582dfdcc3e3e90e4536a9834784b78191bddb6a Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Tue, 24 Sep 2024 14:58:46 +0800 Subject: [PATCH 26/98] Update auth endpoints --- Server/openapi.json | 495 +++++++++++++------------------------------- 1 file changed, 144 insertions(+), 351 deletions(-) diff --git a/Server/openapi.json b/Server/openapi.json index 1f7294be3..b0cb8ebf8 100644 --- a/Server/openapi.json +++ b/Server/openapi.json @@ -128,7 +128,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/UserSuccessResponse" + "$ref": "#/components/schemas/SuccessResponse" } } } @@ -186,7 +186,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/UserSuccessResponse" + "$ref": "#/components/schemas/SuccessResponse" } } } @@ -238,6 +238,38 @@ } } }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SuccessResponse" + } + } + } + }, + "422": { + "description": "Unprocessable Content", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "500": { + "description": "Internal Server Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + }, "security": [ { "bearerAuth": [] @@ -257,24 +289,13 @@ } } ], - "security": [ - { - "bearerAuth": [] - } - ] - } - }, - "/auth/users/admin": { - "get": { - "tags": ["auth"], - "description": "Checks to see if an admin account exists", "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/UserSuccessResponse" + "$ref": "#/components/schemas/SuccessResponse" } } } @@ -299,7 +320,55 @@ } } } - } + }, + "security": [ + { + "bearerAuth": [] + } + ] + } + }, + "/auth/users/superadmin": { + "get": { + "tags": ["auth"], + "description": "Checks to see if an admin account exists", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SuccessResponse" + } + } + } + }, + "422": { + "description": "Unprocessable Content", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "500": { + "description": "Internal Server Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + }, + "security": [ + { + "bearerAuth": [] + } + ] } }, "/auth/users": { @@ -312,7 +381,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/UserSuccessResponse" + "$ref": "#/components/schemas/SuccessResponse" } } } @@ -337,96 +406,41 @@ } } } - } - } - }, - "/auth/invite": { - "post": { - "tags": ["auth"], - "description": "Invite people to application", - "responses": { - "200": { - "description": "OK", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UserSuccessResponse" - } - } - } - }, - "422": { - "description": "Unprocessable Content", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ErrorResponse" - } - } - } - }, - "500": { - "description": "Internal Server Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ErrorResponse" - } - } - } + }, + "security": [ + { + "bearerAuth": [] } - } - } - }, - "/auth/invite/verify": { - "post": { - "tags": ["auth"], - "description": "Verify the invite", - "responses": { - "200": { - "description": "OK", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UserSuccessResponse" - } - } - } - }, - "422": { - "description": "Unprocessable Content", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ErrorResponse" - } - } - } - }, - "500": { - "description": "Internal Server Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ErrorResponse" - } - } - } - } - } + ] } }, "/auth/recovery/request": { "post": { "tags": ["auth"], "description": "Request a recovery token", + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "required": ["email"], + "properties": { + "email": { + "type": "string", + "format": "email" + } + } + } + } + } + }, "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/UserSuccessResponse" + "$ref": "#/components/schemas/SuccessResponse" } } } @@ -458,13 +472,28 @@ "post": { "tags": ["auth"], "description": "Validate recovery token", + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "required": ["recoveryToken"], + "properties": { + "recoveryToken": { + "type": "string" + } + } + } + } + } + }, "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/UserSuccessResponse" + "$ref": "#/components/schemas/SuccessResponse" } } } @@ -496,13 +525,31 @@ "post": { "tags": ["auth"], "description": "Password reset", + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "required": ["recoveryToken", "password"], + "properties": { + "recoveryToken": { + "type": "string" + }, + "password": { + "type": "string" + } + } + } + } + } + }, "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/UserSuccessResponse" + "$ref": "#/components/schemas/SuccessResponse" } } } @@ -529,44 +576,6 @@ } } } - }, - "/healthy": { - "get": { - "tags": ["healthy"], - "description": "Health check", - "responses": { - "200": { - "description": "OK", - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "message": { - "type": "string" - } - } - } - } - } - }, - "500": { - "description": "Internal Server Error", - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "message": { - "type": "string" - } - } - } - } - } - } - } - } } }, "components": { @@ -594,7 +603,8 @@ "type": "object", "properties": { "success": { - "type": "boolean" + "type": "boolean", + "default": true }, "msg": { "type": "string" @@ -642,223 +652,6 @@ "type": "boolean" } } - }, - "UserSuccessResponse": { - "type": "object", - "properties": { - "success": { - "type": "boolean" - }, - "msg": { - "type": "string" - }, - "data": { - "type": "object", - "$ref": "#/components/schemas/UserDataType" - } - } - }, - "MonitorSuccessResponse": { - "type": "object", - "properties": { - "success": { - "type": "boolean" - }, - "msg": { - "type": "string" - }, - "data": { - "type": "object", - "$ref": "#/components/schemas/MonitorDataType" - } - } - }, - "CheckDataSuccessResponse": { - "type": "object", - "properties": { - "success": { - "type": "boolean" - }, - "msg": { - "type": "string" - }, - "data": { - "type": "object", - "$ref": "#/components/schemas/CheckDataType" - } - } - }, - "AlertDataSuccessResponse": { - "type": "object", - "properties": { - "success": { - "type": "boolean" - }, - "msg": { - "type": "string" - }, - "data": { - "type": "object", - "$ref": "#/components/schemas/AlertDataType" - } - } - }, - "UserDataType": { - "type": "object", - "required": [ - "firstname", - "lastname", - "email", - "profilePicUrl", - "isActive", - "isVerified", - "updatedAt", - "createdAt" - ], - "properties": { - "firstname": { - "type": "string" - }, - "lastname": { - "type": "string" - }, - "email": { - "type": "string", - "format": "email" - }, - "profilePicUrl": { - "type": "string" - }, - "isActive": { - "type": "boolean" - }, - "isVerified": { - "type": "boolean" - }, - "updatedAt": { - "type": "string" - }, - "createdAt": { - "type": "string" - } - } - }, - "MonitorDataType": { - "type": "object", - "required": [ - "userId", - "name", - "description", - "url", - "isActive", - "interval", - "updatedAt", - "createdAt" - ], - "properties": { - "userId": { - "type": "string" - }, - "name": { - "type": "string" - }, - "description": { - "type": "string" - }, - "url": { - "type": "string" - }, - "isActive": { - "type": "boolean" - }, - "interval": { - "type": "integer" - }, - "updatedAt": { - "type": "string" - }, - "createdAt": { - "type": "string" - } - } - }, - "CheckDataType": { - "type": "object", - "required": [ - "monitorId", - "status", - "responseTime", - "statusCode", - "message", - "updatedAt", - "createdAt" - ], - "properties": { - "monitorId": { - "type": "string" - }, - "status": { - "type": "string" - }, - "responseTime": { - "type": "integer" - }, - "statusCode": { - "type": "integer" - }, - "message": { - "type": "string" - }, - "updatedAt": { - "type": "string" - }, - "createdAt": { - "type": "string" - } - } - }, - "AlertDataType": { - "type": "object", - "required": [ - "checkId", - "monitorId", - "userId", - "status", - "message", - "notifiedStatus", - "acknowledgedStatus", - "updatedAt", - "createdAt" - ], - "properties": { - "checkId": { - "type": "string" - }, - "monitorId": { - "type": "string" - }, - "userId": { - "type": "string" - }, - "status": { - "type": "string" - }, - "message": { - "type": "string" - }, - "notifiedStatus": { - "type": "boolean" - }, - "acknowledgedStatus": { - "type": "boolean" - }, - "updatedAt": { - "type": "string" - }, - "createdAt": { - "type": "string" - } - } } } } From 0a49a070dbf3efdd69d31b672b34a53b5af08341 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Tue, 24 Sep 2024 15:06:24 +0800 Subject: [PATCH 27/98] Add invite to swagger docs --- Server/openapi.json | 109 +++++++++++++++++++++++++++++++++++++++ Server/validation/joi.js | 1 - 2 files changed, 109 insertions(+), 1 deletion(-) diff --git a/Server/openapi.json b/Server/openapi.json index b0cb8ebf8..e76fcfe5e 100644 --- a/Server/openapi.json +++ b/Server/openapi.json @@ -576,6 +576,115 @@ } } } + }, + "/invite": { + "post": { + "tags": ["invite"], + "description": "Request an invitation", + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "required": ["email", "role"], + "properties": { + "email": { + "type": "string" + }, + "role": { + "type": "array" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SuccessResponse" + } + } + } + }, + "422": { + "description": "Unprocessable Content", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "500": { + "description": "Internal Server Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + } + } + }, + "/invite/verify": { + "post": { + "tags": ["invite"], + "description": "Request an invitation", + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "required": ["token"], + "properties": { + "token": { + "type": "string" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SuccessResponse" + } + } + } + }, + "422": { + "description": "Unprocessable Content", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "500": { + "description": "Internal Server Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + } + } } }, "components": { diff --git a/Server/validation/joi.js b/Server/validation/joi.js index dc82dc73e..60356332e 100644 --- a/Server/validation/joi.js +++ b/Server/validation/joi.js @@ -137,7 +137,6 @@ const inviteBodyValidation = joi.object({ "string.email": "Must be a valid email address", }), role: joi.array().required(), - teamId: joi.string().required(), }); const inviteVerifciationBodyValidation = joi.object({ From c9ab3d9fdef5313ce99824dbaf91d5a210fb977c Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Tue, 24 Sep 2024 15:09:05 +0800 Subject: [PATCH 28/98] Add security to invite docs --- Server/openapi.json | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/Server/openapi.json b/Server/openapi.json index e76fcfe5e..f9afeb03f 100644 --- a/Server/openapi.json +++ b/Server/openapi.json @@ -630,7 +630,12 @@ } } } - } + }, + "security": [ + { + "bearerAuth": [] + } + ] } }, "/invite/verify": { @@ -683,7 +688,12 @@ } } } - } + }, + "security": [ + { + "bearerAuth": [] + } + ] } } }, From 53f2361a1058dedac18d9d39cc0d416f2d930581 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Tue, 24 Sep 2024 15:12:38 +0800 Subject: [PATCH 29/98] add get all monitors to docs --- Server/openapi.json | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/Server/openapi.json b/Server/openapi.json index f9afeb03f..da4ba7d53 100644 --- a/Server/openapi.json +++ b/Server/openapi.json @@ -695,6 +695,49 @@ } ] } + }, + "/monitors": { + "get": { + "tags": ["monitors"], + "description": "Get all monitors", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SuccessResponse" + } + } + } + }, + "422": { + "description": "Unprocessable Content", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "500": { + "description": "Internal Server Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + }, + "security": [ + { + "bearerAuth": [] + } + ] + } } }, "components": { From bd03964ab6b66eb088ff46d54e6aecedb2f78b36 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Tue, 24 Sep 2024 15:20:45 +0800 Subject: [PATCH 30/98] Add get monitor stats by ID to docs --- Server/controllers/monitorController.js | 43 -------------------- Server/openapi.json | 54 +++++++++++++++++++++++++ Server/routes/monitorRoute.js | 1 - Server/validation/joi.js | 9 ----- 4 files changed, 54 insertions(+), 53 deletions(-) diff --git a/Server/controllers/monitorController.js b/Server/controllers/monitorController.js index f5bd98b74..e534e0f60 100644 --- a/Server/controllers/monitorController.js +++ b/Server/controllers/monitorController.js @@ -44,48 +44,6 @@ const getAllMonitors = async (req, res, next) => { } }; -/** - * Returns agregate stats for a monitor - * @async - * @param {Express.Request} req - * @param {Express.Response} res - * @returns {Promise} - * @throws {Error} - */ - -const getMonitorAggregateStats = async (req, res, next) => { - try { - await getMonitorAggregateStatsParamValidation.validateAsync(req.params); - await getMonitorAggregateStatsQueryValidation.validateAsync(req.query); - } catch (error) { - error.status = 422; - error.message = - error.details?.[0]?.message || error.message || "Validation Error"; - next(error); - return; - } - - try { - const { monitorId } = req.params; - const dateRange = req.query.dateRange; - const aggregateStats = await req.db.getMonitorAggregateStats( - monitorId, - dateRange - ); - return res.json({ - success: true, - msg: successMessages.MONTIOR_STATS_BY_ID, - data: aggregateStats, - }); - } catch (error) { - error.service === undefined ? (error.service = SERVICE_NAME) : null; - error.method === undefined - ? (error.method = "getMonitorAggregateStats") - : null; - next(error); - } -}; - /** * Returns monitor stats for monitor with matching ID * @async @@ -516,7 +474,6 @@ const addDemoMonitors = async (req, res, next) => { module.exports = { getAllMonitors, - getMonitorAggregateStats, getMonitorStatsById, getMonitorCertificate, getMonitorById, diff --git a/Server/openapi.json b/Server/openapi.json index da4ba7d53..a4129a8ba 100644 --- a/Server/openapi.json +++ b/Server/openapi.json @@ -738,8 +738,62 @@ } ] } + }, + "/monitors/stats/{monitorId}": { + "get": { + "tags": ["monitors"], + "description": "Get monitor stats", + "parameters": [ + { + "name": "monitorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SuccessResponse" + } + } + } + }, + "422": { + "description": "Unprocessable Content", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "500": { + "description": "Internal Server Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + }, + "security": [ + { + "bearerAuth": [] + } + ] + } } }, + "components": { "securitySchemes": { "bearerAuth": { diff --git a/Server/routes/monitorRoute.js b/Server/routes/monitorRoute.js index c6bec5f0f..aaa9c10e9 100644 --- a/Server/routes/monitorRoute.js +++ b/Server/routes/monitorRoute.js @@ -3,7 +3,6 @@ const monitorController = require("../controllers/monitorController"); const { isAllowed } = require("../middleware/isAllowed"); router.get("/", monitorController.getAllMonitors); -router.get("/aggregate/:monitorId", monitorController.getMonitorAggregateStats); router.get("/stats/:monitorId", monitorController.getMonitorStatsById); router.get("/certificate/:monitorId", monitorController.getMonitorCertificate); router.get("/:monitorId", monitorController.getMonitorById); diff --git a/Server/validation/joi.js b/Server/validation/joi.js index 60356332e..f61432595 100644 --- a/Server/validation/joi.js +++ b/Server/validation/joi.js @@ -235,13 +235,6 @@ const pauseMonitorParamValidation = joi.object({ monitorId: joi.string().required(), }); -const getMonitorAggregateStatsParamValidation = joi.object({ - monitorId: joi.string().required(), -}); -const getMonitorAggregateStatsQueryValidation = joi.object({ - dateRange: joi.string().valid("day", "week", "month"), -}); - //**************************************** // Alerts //**************************************** @@ -407,8 +400,6 @@ module.exports = { getMonitorStatsByIdParamValidation, getMonitorStatsByIdQueryValidation, getCertificateParamValidation, - getMonitorAggregateStatsParamValidation, - getMonitorAggregateStatsQueryValidation, editMonitorBodyValidation, pauseMonitorParamValidation, editUserParamValidation, From fd483b1857560d070f4b6a29ed0e692105c0987f Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Tue, 24 Sep 2024 15:23:40 +0800 Subject: [PATCH 31/98] Add get certificate by monitor ID to docs --- Server/openapi.json | 53 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/Server/openapi.json b/Server/openapi.json index a4129a8ba..7956c2f75 100644 --- a/Server/openapi.json +++ b/Server/openapi.json @@ -791,6 +791,59 @@ } ] } + }, + "/monitors/certificate/{monitorId}": { + "get": { + "tags": ["monitors"], + "description": "Get monitor certificate", + "parameters": [ + { + "name": "monitorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SuccessResponse" + } + } + } + }, + "422": { + "description": "Unprocessable Content", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "500": { + "description": "Internal Server Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + }, + "security": [ + { + "bearerAuth": [] + } + ] + } } }, From 1697e853e64114fe41f9b708f95008bd6d5ce85d Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Tue, 24 Sep 2024 15:27:01 +0800 Subject: [PATCH 32/98] Add getMonitorById to docs --- Server/openapi.json | 53 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/Server/openapi.json b/Server/openapi.json index 7956c2f75..595f2a0ce 100644 --- a/Server/openapi.json +++ b/Server/openapi.json @@ -739,6 +739,59 @@ ] } }, + "/monitors/{monitorId}": { + "get": { + "tags": ["monitors"], + "description": "Get monitor by id", + "parameters": [ + { + "name": "monitorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SuccessResponse" + } + } + } + }, + "422": { + "description": "Unprocessable Content", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "500": { + "description": "Internal Server Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + }, + "security": [ + { + "bearerAuth": [] + } + ] + } + }, "/monitors/stats/{monitorId}": { "get": { "tags": ["monitors"], From db4dbc6a5f6be5a4aeee8f7388477deaecfdacef Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Tue, 24 Sep 2024 15:38:27 +0800 Subject: [PATCH 33/98] Add getMonitorsAndSummaryByTeamID to docs --- Server/openapi.json | 62 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) diff --git a/Server/openapi.json b/Server/openapi.json index 595f2a0ce..ef6a8ae2c 100644 --- a/Server/openapi.json +++ b/Server/openapi.json @@ -897,6 +897,68 @@ } ] } + }, + "/monitors/team/summary/{teamId}": { + "get": { + "tags": ["monitors"], + "description": "Get monitors and summary by teamId", + "parameters": [ + { + "name": "teamId", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "type", + "in": "query", + "required": false, + "schema": { + "type": "array", + "enum": ["http", "ping", "pagespeed"] + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SuccessResponse" + } + } + } + }, + "422": { + "description": "Unprocessable Content", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "500": { + "description": "Internal Server Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + }, + "security": [ + { + "bearerAuth": [] + } + ] + } } }, From e314def79a5763768b7ec706d6a8f430cf33128c Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Wed, 25 Sep 2024 10:09:56 +0800 Subject: [PATCH 34/98] Add conditional rendering to PageSpeed pages for non admin users --- Client/src/App.jsx | 15 ++++--- .../src/Pages/PageSpeed/Configure/index.jsx | 2 +- Client/src/Pages/PageSpeed/Details/index.jsx | 41 ++++++++++--------- Client/src/Pages/PageSpeed/index.jsx | 18 ++++---- 4 files changed, 42 insertions(+), 34 deletions(-) diff --git a/Client/src/App.jsx b/Client/src/App.jsx index 09fcfcf5f..ca3894c28 100644 --- a/Client/src/App.jsx +++ b/Client/src/App.jsx @@ -19,13 +19,13 @@ import SetNewPassword from "./Pages/Auth/SetNewPassword"; import NewPasswordConfirmed from "./Pages/Auth/NewPasswordConfirmed"; import ProtectedRoute from "./Components/ProtectedRoute"; import Details from "./Pages/Monitors/Details"; -import Maintenance from "./Pages/Maintenance"; +// import Maintenance from "./Pages/Maintenance"; import withAdminCheck from "./HOC/withAdminCheck"; import withAdminProp from "./HOC/withAdminProp"; import Configure from "./Pages/Monitors/Configure"; import PageSpeed from "./Pages/PageSpeed"; import CreatePageSpeed from "./Pages/PageSpeed/CreatePageSpeed"; -import CreateNewMaintenanceWindow from "./Pages/Maintenance/CreateMaintenanceWindow"; +// import CreateNewMaintenanceWindow from "./Pages/Maintenance/CreateMaintenanceWindow"; import PageSpeedDetails from "./Pages/PageSpeed/Details"; import PageSpeedConfigure from "./Pages/PageSpeed/Configure"; import { ThemeProvider } from "@emotion/react"; @@ -37,9 +37,10 @@ import { CssBaseline } from "@mui/material"; function App() { const AdminCheckedRegister = withAdminCheck(Register); const MonitorsWithAdminProp = withAdminProp(Monitors); - const DetailsWithAdminProp = withAdminProp(Details); + const MonitorDetailsWithAdminProp = withAdminProp(Details); const PageSpeedWithAdminProp = withAdminProp(PageSpeed); - const MaintenanceWithAdminProp = withAdminProp(Maintenance); + const PageSpeedDetailsWithAdminProp = withAdminProp(PageSpeedDetails); + // const MaintenanceWithAdminProp = withAdminProp(Maintenance); const SettingsWithAdminProp = withAdminProp(Settings); const mode = useSelector((state) => state.ui.mode); @@ -64,7 +65,7 @@ function App() { /> } + element={} /> } + element={ + + } /> { }, }} > - Editting... + Editing... diff --git a/Client/src/Pages/PageSpeed/Details/index.jsx b/Client/src/Pages/PageSpeed/Details/index.jsx index 8fc137223..e2c9a606d 100644 --- a/Client/src/Pages/PageSpeed/Details/index.jsx +++ b/Client/src/Pages/PageSpeed/Details/index.jsx @@ -32,7 +32,7 @@ import PieChart from "./Charts/PieChart"; import useUtils from "../../Monitors/utils"; import "./index.css"; -const PageSpeedDetails = () => { +const PageSpeedDetails = ({ isAdmin }) => { const theme = useTheme(); const navigate = useNavigate(); const { statusColor, pagespeedStatusMsg, determineState } = useUtils(); @@ -157,25 +157,27 @@ const PageSpeedDetails = () => { - + }} + > + + Configure + + )} @@ -393,6 +395,7 @@ const PageSpeedDetails = () => { }; PageSpeedDetails.propTypes = { + isAdmin: PropTypes.bool, push: PropTypes.func, }; diff --git a/Client/src/Pages/PageSpeed/index.jsx b/Client/src/Pages/PageSpeed/index.jsx index 3e78b1d6b..3174013ef 100644 --- a/Client/src/Pages/PageSpeed/index.jsx +++ b/Client/src/Pages/PageSpeed/index.jsx @@ -87,14 +87,16 @@ const PageSpeed = ({ isAdmin }) => { mt={theme.spacing(5)} > - + {isAdmin && ( + + )} From fe97390e53de865ffc85f9fb6ef8fc961593a458 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Wed, 25 Sep 2024 10:54:56 +0800 Subject: [PATCH 35/98] Added put and delete to monitors docs --- Server/openapi.json | 266 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 266 insertions(+) diff --git a/Server/openapi.json b/Server/openapi.json index ef6a8ae2c..8e71d07a0 100644 --- a/Server/openapi.json +++ b/Server/openapi.json @@ -737,6 +737,97 @@ "bearerAuth": [] } ] + }, + "post": { + "tags": ["monitors"], + "description": "Create a new monitor", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateMonitorBody" + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SuccessResponse" + } + } + } + }, + "422": { + "description": "Unprocessable Content", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "500": { + "description": "Internal Server Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + }, + "security": [ + { + "bearerAuth": [] + } + ] + }, + "delete": { + "tags": ["monitors"], + "description": "Delete all monitors", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SuccessResponse" + } + } + } + }, + "422": { + "description": "Unprocessable Content", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "500": { + "description": "Internal Server Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + }, + "security": [ + { + "bearerAuth": [] + } + ] } }, "/monitors/{monitorId}": { @@ -959,6 +1050,141 @@ } ] } + }, + "/monitors/team/{teamId}": { + "get": { + "tags": ["monitors"], + "description": "Get monitors by teamId", + "parameters": [ + { + "name": "teamId", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "status", + "description": "Status of monitor, true for up, false for down", + "in": "query", + "required": false, + "schema": { + "type": "boolean" + } + }, + { + "name": "checkOrder", + "description": "Order of checks", + "in": "query", + "required": false, + "schema": { + "type": "string", + "enum": ["asc", "desc"] + } + }, + { + "name": "limit", + "description": "Number of checks to return with monitor", + "in": "query", + "required": false, + "schema": { + "type": "integer" + } + }, + { + "name": "type", + "description": "Type of monitor", + "in": "query", + "required": false, + "schema": { + "type": "string", + "enum": ["http", "ping", "pagespeed"] + } + }, + { + "name": "page", + "in": "query", + "required": false, + "schema": { + "type": "integer" + } + }, + { + "name": "rowsPerPage", + "in": "query", + "required": false, + "schema": { + "type": "integer" + } + }, + { + "name": "filter", + "description": "Value to filter by", + "in": "query", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "field", + "description": "Field to filter on", + "in": "query", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "order", + "description": "Sort order of results", + "in": "query", + "required": false, + "schema": { + "type": "string", + "enum": ["http", "ping", "pagespeed"] + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SuccessResponse" + } + } + } + }, + "422": { + "description": "Unprocessable Content", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "500": { + "description": "Internal Server Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + }, + "security": [ + { + "bearerAuth": [] + } + ] + } } }, @@ -1036,6 +1262,46 @@ "type": "boolean" } } + }, + "CreateMonitorBody": { + "type": "object", + "required": ["userId", "teamId", "name", "description", "type", "url"], + "properties": { + "_id": { + "type": "string" + }, + "userId": { + "type": "string" + }, + "teamId": { + "type": "string" + }, + "name": { + "type": "string" + }, + "description": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["http", "ping", "pagespeed"] + }, + "url": { + "type": "string" + }, + "isActive": { + "type": "boolean" + }, + "interval": { + "type": "integer" + }, + "notifications": { + "type": "array", + "items": { + "type": "string" + } + } + } } } } From 17f2039fc221b69befcc6e731fa91917cf769378 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Wed, 25 Sep 2024 10:57:44 +0800 Subject: [PATCH 36/98] Add delete to monitors/:monitorId doc --- Server/openapi.json | 51 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/Server/openapi.json b/Server/openapi.json index 8e71d07a0..e03ca93ac 100644 --- a/Server/openapi.json +++ b/Server/openapi.json @@ -881,6 +881,57 @@ "bearerAuth": [] } ] + }, + "delete": { + "tags": ["monitors"], + "description": "Delete monitor by id", + "parameters": [ + { + "name": "monitorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SuccessResponse" + } + } + } + }, + "422": { + "description": "Unprocessable Content", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "500": { + "description": "Internal Server Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + }, + "security": [ + { + "bearerAuth": [] + } + ] } }, "/monitors/stats/{monitorId}": { From 24863a2fb72cc8d516fac95126a117ccb1a2d811 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Wed, 25 Sep 2024 11:03:50 +0800 Subject: [PATCH 37/98] Add put to monitors/:monitorId doc --- Server/openapi.json | 80 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) diff --git a/Server/openapi.json b/Server/openapi.json index e03ca93ac..0d07292e6 100644 --- a/Server/openapi.json +++ b/Server/openapi.json @@ -882,6 +882,66 @@ } ] }, + "put": { + "tags": ["monitors"], + "description": "Update monitor by id", + "parameters": [ + { + "name": "monitorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UpdateMonitorBody" + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SuccessResponse" + } + } + } + }, + "422": { + "description": "Unprocessable Content", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "500": { + "description": "Internal Server Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + }, + "security": [ + { + "bearerAuth": [] + } + ] + }, "delete": { "tags": ["monitors"], "description": "Delete monitor by id", @@ -1353,6 +1413,26 @@ } } } + }, + "UpdateMonitorBody": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "description": { + "type": "string" + }, + "interval": { + "type": "integer" + }, + "notifications": { + "type": "array", + "items": { + "type": "string" + } + } + } } } } From 7a78a6d6b0d02c6e0691e94ab748714f3379d454 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Wed, 25 Sep 2024 11:10:05 +0800 Subject: [PATCH 38/98] Add pause and add demo routes to docs --- Server/openapi.json | 105 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 105 insertions(+) diff --git a/Server/openapi.json b/Server/openapi.json index 0d07292e6..0117c8b0f 100644 --- a/Server/openapi.json +++ b/Server/openapi.json @@ -1296,6 +1296,111 @@ } ] } + }, + "/monitors/pause/{monitorId}": { + "post": { + "tags": ["monitors"], + "description": "Pause monitor", + "parameters": [ + { + "name": "monitorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SuccessResponse" + } + } + } + }, + "422": { + "description": "Unprocessable Content", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "500": { + "description": "Internal Server Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + }, + "security": [ + { + "bearerAuth": [] + } + ] + } + }, + "/monitors/demo": { + "post": { + "tags": ["monitors"], + "description": "Create a demo monitor", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateMonitorBody" + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SuccessResponse" + } + } + } + }, + "422": { + "description": "Unprocessable Content", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "500": { + "description": "Internal Server Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + }, + "security": [ + { + "bearerAuth": [] + } + ] + } } }, From 05f1b2b6b463895d41c10b3135bfea95f4f9d457 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Wed, 25 Sep 2024 11:23:36 +0800 Subject: [PATCH 39/98] Add getCheck createCheck routes to docs --- Server/openapi.json | 140 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 140 insertions(+) diff --git a/Server/openapi.json b/Server/openapi.json index 0117c8b0f..28718098f 100644 --- a/Server/openapi.json +++ b/Server/openapi.json @@ -1401,6 +1401,119 @@ } ] } + }, + "/checks/{monitorId}": { + "get": { + "tags": ["checks"], + "description": "Get all checks for a monitor", + "parameters": [ + { + "name": "monitorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SuccessResponse" + } + } + } + }, + "422": { + "description": "Unprocessable Content", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "500": { + "description": "Internal Server Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + }, + "security": [ + { + "bearerAuth": [] + } + ] + }, + "post": { + "tags": ["checks"], + "description": "Create a new check", + "parameters": [ + { + "name": "monitorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateCheckBody" + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SuccessResponse" + } + } + } + }, + "422": { + "description": "Unprocessable Content", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "500": { + "description": "Internal Server Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + }, + "security": [ + { + "bearerAuth": [] + } + ] + } } }, @@ -1538,6 +1651,33 @@ } } } + }, + "CreateCheckBody": { + "type": "object", + "required": [ + "monitorId", + "status", + "responseTime", + "statusCode", + "message" + ], + "properties": { + "monitorId": { + "type": "string" + }, + "status": { + "type": "boolean" + }, + "responseTime": { + "type": "integer" + }, + "statusCode": { + "type": "integer" + }, + "message": { + "type": "string" + } + } } } } From 885a89e36b6b8a01e656a231bfef1465fe1f691b Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Wed, 25 Sep 2024 11:29:20 +0800 Subject: [PATCH 40/98] Add getChecksByTeam route --- Server/openapi.json | 104 ++++++++++++++++++++++++++++++++++++ Server/routes/checkRoute.js | 8 ++- 2 files changed, 107 insertions(+), 5 deletions(-) diff --git a/Server/openapi.json b/Server/openapi.json index 28718098f..d33fb03e1 100644 --- a/Server/openapi.json +++ b/Server/openapi.json @@ -1513,6 +1513,110 @@ "bearerAuth": [] } ] + }, + "delete": { + "tags": ["checks"], + "description": "Delete all checks for a monitor", + "parameters": [ + { + "name": "monitorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SuccessResponse" + } + } + } + }, + "422": { + "description": "Unprocessable Content", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "500": { + "description": "Internal Server Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + }, + "security": [ + { + "bearerAuth": [] + } + ] + } + }, + "/checks/team/{teamId}": { + "get": { + "tags": ["checks"], + "description": "Get all checks for a team", + "parameters": [ + { + "name": "teamId", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SuccessResponse" + } + } + } + }, + "422": { + "description": "Unprocessable Content", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "500": { + "description": "Internal Server Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + }, + "security": [ + { + "bearerAuth": [] + } + ] } } }, diff --git a/Server/routes/checkRoute.js b/Server/routes/checkRoute.js index a26e9eb94..84e7f47a8 100644 --- a/Server/routes/checkRoute.js +++ b/Server/routes/checkRoute.js @@ -4,22 +4,20 @@ const { verifyOwnership } = require("../middleware/verifyOwnership"); const { isAllowed } = require("../middleware/isAllowed"); const Monitor = require("../models/Monitor"); +router.get("/:monitorId", checkController.getChecks); router.post( "/:monitorId", verifyOwnership(Monitor, "monitorId"), checkController.createCheck ); - -router.get("/:monitorId", checkController.getChecks); - -router.get("/team/:teamId", checkController.getTeamChecks); - router.delete( "/:monitorId", verifyOwnership(Monitor, "monitorId"), checkController.deleteChecks ); +router.get("/team/:teamId", checkController.getTeamChecks); + router.delete( "/team/:teamId", isAllowed(["admin", "superadmin"]), From c44152de93ea4812bc9fe4f84b2b0833f7f999d1 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Wed, 25 Sep 2024 11:30:59 +0800 Subject: [PATCH 41/98] Add deleteChecksByTeam route --- Server/openapi.json | 51 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/Server/openapi.json b/Server/openapi.json index d33fb03e1..b1b23ce4b 100644 --- a/Server/openapi.json +++ b/Server/openapi.json @@ -1617,6 +1617,57 @@ "bearerAuth": [] } ] + }, + "delete": { + "tags": ["checks"], + "description": "Delete all checks for a team", + "parameters": [ + { + "name": "teamId", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SuccessResponse" + } + } + } + }, + "422": { + "description": "Unprocessable Content", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "500": { + "description": "Internal Server Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + }, + "security": [ + { + "bearerAuth": [] + } + ] } } }, From 36014fada2b4c185feeaa48c05ebd34faafa5a25 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Wed, 25 Sep 2024 11:37:52 +0800 Subject: [PATCH 42/98] refactor ttl endpoint path, add /team/ttl to docs --- Client/src/Utils/NetworkService.js | 2 +- Server/openapi.json | 61 ++++++++++++++++++++++++++++++ Server/routes/checkRoute.js | 2 +- 3 files changed, 63 insertions(+), 2 deletions(-) diff --git a/Client/src/Utils/NetworkService.js b/Client/src/Utils/NetworkService.js index c087fb73a..905385e70 100644 --- a/Client/src/Utils/NetworkService.js +++ b/Client/src/Utils/NetworkService.js @@ -609,7 +609,7 @@ class NetworkService { */ async updateChecksTTL(config) { return this.axiosInstance.put( - `/checks/ttl`, + `/checks/team/ttl`, { ttl: config.ttl }, { headers: { diff --git a/Server/openapi.json b/Server/openapi.json index b1b23ce4b..dd9a3ae8b 100644 --- a/Server/openapi.json +++ b/Server/openapi.json @@ -1669,6 +1669,58 @@ } ] } + }, + "/checks/team/ttl": { + "put": { + "tags": ["checks"], + "description": "Update check TTL", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UpdateCheckTTLBody" + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SuccessResponse" + } + } + } + }, + "422": { + "description": "Unprocessable Content", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "500": { + "description": "Internal Server Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + }, + "security": [ + { + "bearerAuth": [] + } + ] + } } }, @@ -1833,6 +1885,15 @@ "type": "string" } } + }, + "UpdateCheckTTLBody": { + "type": "object", + "required": ["ttl"], + "properties": { + "ttl": { + "type": "integer" + } + } } } } diff --git a/Server/routes/checkRoute.js b/Server/routes/checkRoute.js index 84e7f47a8..fe99e7271 100644 --- a/Server/routes/checkRoute.js +++ b/Server/routes/checkRoute.js @@ -25,7 +25,7 @@ router.delete( ); router.put( - "/ttl", + "/team/ttl", isAllowed(["admin", "superadmin"]), checkController.updateChecksTTL ); From 115831ca34f49725ba9d74e6673d002757e1aa77 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Wed, 25 Sep 2024 11:41:50 +0800 Subject: [PATCH 43/98] Remove unsued alert module --- Server/controllers/alertController.js | 192 ------------------------- Server/db/mongo/MongoDB.js | 21 --- Server/db/mongo/modules/alertModule.js | 140 ------------------ Server/index.js | 2 - Server/models/Alert.js | 38 ----- Server/routes/alertRoute.js | 44 ------ 6 files changed, 437 deletions(-) delete mode 100644 Server/controllers/alertController.js delete mode 100644 Server/db/mongo/modules/alertModule.js delete mode 100644 Server/models/Alert.js delete mode 100644 Server/routes/alertRoute.js diff --git a/Server/controllers/alertController.js b/Server/controllers/alertController.js deleted file mode 100644 index cd31db565..000000000 --- a/Server/controllers/alertController.js +++ /dev/null @@ -1,192 +0,0 @@ -const logger = require("../utils/logger"); -require("dotenv").config(); -const { - createAlertParamValidation, - createAlertBodyValidation, - getAlertsByUserIdParamValidation, - getAlertsByMonitorIdParamValidation, - getAlertByIdParamValidation, - editAlertParamValidation, - editAlertBodyValidation, - deleteAlertParamValidation, -} = require("../validation/joi"); -const { successMessages } = require("../utils/messages"); -const SERVICE_NAME = "alertController"; - -/** - * Creates an alert for a monitor - * @async - * @param {Express.Request} req - * @param {Express.Response} res - * @returns {Promise} - * @throws {Error} - */ -const createAlert = async (req, res, next) => { - try { - await createAlertParamValidation.validateAsync(req.params); - await createAlertBodyValidation.validateAsync(req.body); - } catch (error) { - error.status = 422; - error.message = - error.details?.[0]?.message || error.message || "Validation Error"; - error.service = SERVICE_NAME; - next(error); - return; - } - - try { - const alertData = { ...req.body }; - const alert = await req.db.createAlert(alertData); - return res - .status(200) - .json({ success: true, msg: successMessages.ALERT_CREATE, data: alert }); - } catch (error) { - error.service === undefined ? (error.service = SERVICE_NAME) : null; - error.method === undefined ? (error.method = "createAlert") : null; - next(error); - } -}; - -/** - * Gets all alerts for a user - * @async - * @param {Express.Request} req - * @param {Express.Response} res - * @returns {Promise} - * @throws {Error} - */ -const getAlertsByUserId = async (req, res, next) => { - try { - await getAlertsByUserIdParamValidation.validateAsync(req.params); - } catch (error) { - error.status = 422; - error.message = - error.details?.[0]?.message || error.message || "Validation Error"; - error.service = SERVICE_NAME; - next(error); - return; - } - - try { - const alerts = await req.db.getAlertsByUserId(req.params.userId); - return res.status(200).json({ - success: true, - msg: successMessages.ALERT_GET_BY_USER, - data: alerts, - }); - } catch (error) { - error.service = SERVICE_NAME; - next(error); - } -}; - -const getAlertsByMonitorId = async (req, res, next) => { - try { - await getAlertsByMonitorIdParamValidation.validateAsync(req.params); - } catch (error) { - error.status = 422; - error.message = - error.details?.[0]?.message || error.message || "Validation Error"; - error.service = SERVICE_NAME; - next(error); - return; - } - - try { - const alerts = await req.db.getAlertsByMonitorId(req.params.monitorId); - return res.status(200).json({ - success: true, - msg: successMessages.ALERT_GET_BY_MONITOR, - data: alerts, - }); - } catch (error) { - error.service = SERVICE_NAME; - next(error); - } -}; - -const getAlertById = async (req, res, next) => { - try { - await getAlertByIdParamValidation.validateAsync(req.params); - } catch (error) { - error.status = 422; - error.message = - error.details?.[0]?.message || error.message || "Validation Error"; - error.service = SERVICE_NAME; - next(error); - return; - } - - try { - const alert = await req.db.getAlertById(req.params.alertId); - return res.status(200).json({ - success: true, - msg: successMessages.ALERT_GET_BY_ID, - data: alert, - }); - } catch (error) { - error.service = SERVICE_NAME; - next(error); - } -}; - -const editAlert = async (req, res, next) => { - try { - await editAlertParamValidation.validateAsync(req.params); - await editAlertBodyValidation.validateAsync(req.body); - } catch (error) { - console.log(error); - error.status = 422; - error.message = - error.details?.[0]?.message || error.message || "Validation Error"; - error.service = SERVICE_NAME; - next(error); - return; - } - - try { - const alertData = { ...req.body }; - const alert = await req.db.editAlert(req.params.alertId, alertData); - return res.status(200).json({ - success: true, - msg: successMessages.ALERT_EDIT, - data: alert, - }); - } catch (error) { - error.service = SERVICE_NAME; - next(error); - } -}; -const deleteAlert = async (req, res, next) => { - try { - await deleteAlertParamValidation.validateAsync(req.params); - } catch (error) { - error.status = 422; - error.message = - error.details?.[0]?.message || error.message || "Validation Error"; - error.service = SERVICE_NAME; - next(error); - return; - } - - try { - const deleted = await req.db.deleteAlert(req.params.alertId); - return res.status(200).json({ - success: true, - msg: successMessages.ALERT_DELETE, - data: deleted, - }); - } catch (error) { - error.service = SERVICE_NAME; - next(error); - } -}; - -module.exports = { - createAlert, - getAlertsByUserId, - getAlertsByMonitorId, - getAlertById, - editAlert, - deleteAlert, -}; diff --git a/Server/db/mongo/MongoDB.js b/Server/db/mongo/MongoDB.js index ebc50f7da..c5fcff08c 100644 --- a/Server/db/mongo/MongoDB.js +++ b/Server/db/mongo/MongoDB.js @@ -100,20 +100,6 @@ const { updateChecksTTL, } = require("./modules/checkModule"); -//**************************************** -// Alerts -//**************************************** - -const { - createAlert, - getAlertsByUserId, - getAlertsByMonitorId, - getAlertById, - editAlert, - deleteAlert, - deleteAlertByMonitorId, -} = require("./modules/alertModule"); - //**************************************** // Maintenance Window //**************************************** @@ -163,13 +149,6 @@ module.exports = { deleteChecks, deleteChecksByTeamId, updateChecksTTL, - createAlert, - getAlertsByUserId, - getAlertsByMonitorId, - getAlertById, - editAlert, - deleteAlert, - deleteAlertByMonitorId, deleteMonitorsByUserId, createPageSpeedCheck, getPageSpeedChecks, diff --git a/Server/db/mongo/modules/alertModule.js b/Server/db/mongo/modules/alertModule.js deleted file mode 100644 index b9e65647b..000000000 --- a/Server/db/mongo/modules/alertModule.js +++ /dev/null @@ -1,140 +0,0 @@ -const Alert = require("../../../models/Alert"); - -/** - * Creates an Alert associated with a Monitor and User - * @async - * @param {Object} alertData - * @param {string} alertData.checkId - * @param {string} alert.monitorId - * @param {string} alert.userId - * @param {boolean} alert.status - * @param {string} alert.message - * @param {boolean} alert.notifiedStatus - * @param {boolean} alert.acknowledgeStatus - * @returns {>} - * @throws {Error} - */ -const createAlert = async (alertData) => { - try { - const alert = await new Alert({ ...alertData }).save(); - return alert; - } catch (error) { - throw error; - } -}; - -/** - * Gets all alerts a User has set - * @async - * @param {string} userId - * @returns {>} - * @throws {Error} - */ -const getAlertsByUserId = async (userId) => { - try { - const alerts = await Alert.find({ userId }); - return alerts; - } catch (error) { - throw error; - } -}; - -/** - * Gets all alerts a for an associated Monitor - * @async - * @param {string} monitorId - * @returns {>} - * @throws {Error} - */ -const getAlertsByMonitorId = async (monitorId) => { - try { - const alerts = await Alert.find({ monitorId }); - return alerts; - } catch (error) { - throw error; - } -}; - -/** - * Returns an alert with specified ID - * @async - * @param {string} alertId - * @returns {Promise} - * @throws {Error} - */ -const getAlertById = async (alertId) => { - try { - const alert = await Alert.findById(alertId); - return alert; - } catch (error) { - throw error; - } -}; - -/** - * Returns an edited alert with the specified ID - * @async - * @param {string} alertId - * @param {Object} alertData - * @param {string} alertData.checkId - * @param {string} alertData.monitorId - * @param {string} alertData.userId - * @param {boolean} alertData.status - * @param {string} alertData.message - * @param {boolean} alertData.notifiedStatus - * @param {boolean} alertData.acknowledgeStatus - * @param {Express.Response} res - * @returns {Promise>} - * @throws {Error} - */ -const editAlert = async (alertId, alertData) => { - try { - const editedAlert = await Alert.findByIdAndUpdate(alertId, alertData, { - new: true, - }); - return editedAlert; - } catch (error) { - throw error; - } -}; - -/** - * Deletes an alert with the specified ID - * @async - * @param {string} alertId - * @throws {Error} - */ -const deleteAlert = async (alertId) => { - try { - const result = await Alert.findByIdAndDelete(alertId); - return result; - } catch (error) { - throw error; - } -}; - -/** - * Deletes alerts by monitor ID. - * - * @param {string} monitorId - The ID of the monitor. - * @returns {Promise} A promise that resolves to the result of the delete operation. - * @throws {Error} If an error occurs while deleting the alerts. - */ -const deleteAlertByMonitorId = async (monitorId) => { - try { - const result = await Alert.deleteMany({ monitorId }); - return result; - } catch (error) { - throw error; - } -}; - -module.exports = { - createAlert, - getAlertsByUserId, - getAlertsByMonitorId, - getAlertById, - editAlert, - deleteAlert, - deleteAlertByMonitorId, -}; diff --git a/Server/index.js b/Server/index.js index 672aa4882..e665f21d2 100644 --- a/Server/index.js +++ b/Server/index.js @@ -14,7 +14,6 @@ const authRouter = require("./routes/authRoute"); const inviteRouter = require("./routes/inviteRoute"); const monitorRouter = require("./routes/monitorRoute"); const checkRouter = require("./routes/checkRoute"); -const alertRouter = require("./routes/alertRoute"); const pageSpeedCheckRouter = require("./routes/pageSpeedCheckRoute"); const maintenanceWindowRouter = require("./routes/maintenanceWindowRoute"); @@ -85,7 +84,6 @@ const startApp = async () => { app.use("/api/v1/invite", inviteRouter); app.use("/api/v1/monitors", verifyJWT, monitorRouter); app.use("/api/v1/checks", verifyJWT, checkRouter); - app.use("/api/v1/alerts", verifyJWT, alertRouter); app.use("/api/v1/pagespeed", verifyJWT, pageSpeedCheckRouter); app.use("/api/v1/maintenance-window", verifyJWT, maintenanceWindowRouter); //Temporary route for testing, remove later diff --git a/Server/models/Alert.js b/Server/models/Alert.js deleted file mode 100644 index 758a7eba2..000000000 --- a/Server/models/Alert.js +++ /dev/null @@ -1,38 +0,0 @@ -const mongoose = require('mongoose') - -const AlertSchema = mongoose.Schema( - { - checkId: { - type: mongoose.Schema.Types.ObjectId, - ref: 'Check', - immutable: true, - }, - monitorId: { - type: mongoose.Schema.Types.ObjectId, - ref: 'Monitor', - immutable: true, - }, - userId: { - type: mongoose.Schema.Types.ObjectId, - ref: 'User', - immutable: true, - }, - status: { - type: Boolean, - }, - message: { - type: String, - }, - notifiedStatus: { - type: Boolean, - }, - acknowledgeStatus: { - type: Boolean, - } - }, - { - timestamps: true, - } -); - -module.exports = mongoose.model('Alert', AlertSchema); diff --git a/Server/routes/alertRoute.js b/Server/routes/alertRoute.js deleted file mode 100644 index 434c0495a..000000000 --- a/Server/routes/alertRoute.js +++ /dev/null @@ -1,44 +0,0 @@ -const router = require("express").Router(); -const alertController = require("../controllers/alertController"); -const { verifyOwnership } = require("../middleware/verifyOwnership"); -const Alert = require("../models/Alert"); -const Monitor = require("../models/Monitor"); - -// Create alert -router.post( - "/:monitorId", - verifyOwnership(Monitor, "monitorId"), - alertController.createAlert -); -// Get all alerts for a user -router.get( - "/user/:userId", - verifyOwnership(Monitor, "monitorId"), - alertController.getAlertsByUserId -); -// Get all alerts for a monitor -router.get( - "/monitor/:monitorId", - verifyOwnership(Monitor, "monitorId"), - alertController.getAlertsByMonitorId -); -// Get a single alert -router.get( - "/:alertId", - verifyOwnership(Monitor, "monitorId"), - alertController.getAlertById -); -// Edit -router.put( - "/:alertId", - verifyOwnership(Monitor, "monitorId"), - alertController.editAlert -); -//Delete -router.delete( - "/:alertId", - verifyOwnership(Monitor, "monitorId"), - alertController.deleteAlert -); - -module.exports = router; From d849374225828db219b2171b2e0409f381a8b5a9 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Wed, 25 Sep 2024 11:49:28 +0800 Subject: [PATCH 44/98] remove unused routes from docs --- Server/openapi.json | 16 ---------------- 1 file changed, 16 deletions(-) diff --git a/Server/openapi.json b/Server/openapi.json index dd9a3ae8b..2c5097649 100644 --- a/Server/openapi.json +++ b/Server/openapi.json @@ -50,25 +50,9 @@ "name": "checks", "description": "Checks" }, - { - "name": "alerts", - "description": "Alerts" - }, - { - "name": "pagespeed", - "description": "Page Speed" - }, { "name": "maintenance-window", "description": "Maintenance window" - }, - { - "name": "healthy", - "description": "Health check" - }, - { - "name": "mail", - "description": "Mail service" } ], "paths": { From f2407ac5fa7ea04ee729f63966009ba3e5494e97 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Wed, 25 Sep 2024 11:52:39 +0800 Subject: [PATCH 45/98] Remove unused pagespeed modules --- .../controllers/pageSpeedCheckController.js | 129 ------------------ Server/index.js | 2 - Server/routes/pageSpeedCheckRoute.js | 45 ------ 3 files changed, 176 deletions(-) delete mode 100644 Server/controllers/pageSpeedCheckController.js delete mode 100644 Server/routes/pageSpeedCheckRoute.js diff --git a/Server/controllers/pageSpeedCheckController.js b/Server/controllers/pageSpeedCheckController.js deleted file mode 100644 index b07fac4d7..000000000 --- a/Server/controllers/pageSpeedCheckController.js +++ /dev/null @@ -1,129 +0,0 @@ -const PageSpeedService = require("../service/pageSpeedService"); -const { successMessages } = require("../utils/messages"); -const pageSpeedService = new PageSpeedService(); -const SERVICE_NAME = "pagespeedCheckController"; -const { - getPageSpeedCheckParamValidation, - createPageSpeedCheckParamValidation, - createPageSpeedCheckBodyValidation, - deletePageSpeedCheckParamValidation, -} = require("../validation/joi"); - -/** - * Gets all PageSpeedChecks for a monitor - * @async - * @param {Express.Request} req - The request object - * @param {Express.Response} res - The response object - * @param {Function} next - The next middleware function - * @returns {Promise} - */ -const getPageSpeedChecks = async (req, res, next) => { - try { - // Validate monitorId parameter - await getPageSpeedCheckParamValidation.validateAsync(req.params); - } catch (error) { - error.status = 422; - error.service = SERVICE_NAME; - error.message = - error.details?.[0]?.message || error.message || "Validation Error"; - next(error); - return; - } - - try { - return res.status(200).json({ msg: "Hit getPageSpeedChecks" }); - } catch (error) { - error.service === undefined ? (error.service = SERVICE_NAME) : null; - error.method === undefined ? (error.method = "getPageSpeedChecks") : null; - next(error); - } -}; - -/** - * Creates a new PageSpeedCheck for a monitor - * @async - * @param {Express.Request} req - The request object - * @param {Express.Response} res - The response object - * @param {Function} next - The next middleware function - * @returns {Promise} - */ -const createPageSpeedCheck = async (req, res, next) => { - try { - await createPageSpeedCheckParamValidation.validateAsync(req.params); - await createPageSpeedCheckBodyValidation.validateAsync(req.body); - } catch (error) { - error.status = 422; - error.service = SERVICE_NAME; - error.message = - error.details?.[0]?.message || error.message || "Validation Error"; - next(error); - return; - } - - try { - const { monitorId } = req.params; - const { url } = req.body; - - // Run the PageSpeed check - const pageSpeedResults = await pageSpeedService.runPageSpeedCheck(url); - - // Extract categories scores - const categories = pageSpeedResults.lighthouseResult?.categories; - - if (!categories) { - throw new Error("Categories not found in PageSpeed results"); - } - - const newPageSpeedCheck = await pageSpeedService.createPageSpeedCheck({ - monitorId, - accessibility: (categories.accessibility?.score || 0) * 100, - bestPractices: (categories["best-practices"]?.score || 0) * 100, - seo: (categories.seo?.score || 0) * 100, - performance: (categories.performance?.score || 0) * 100, - }); - - return res.status(201).json({ - msg: successMessages.CREATED, - data: newPageSpeedCheck, - }); - } catch (error) { - error.service === undefined ? (error.service = SERVICE_NAME) : null; - error.method === undefined ? (error.method = "createPageSpeedCheck") : null; - next(error); - } -}; - -/** - * Deletes all PageSpeedChecks for a monitor - * @async - * @param {Express.Request} req - The request object - * @param {Express.Response} res - The response object - * @param {Function} next - The next middleware function - * @returns {Promise} - */ -const deletePageSpeedCheck = async (req, res, next) => { - try { - // Validate monitorId parameter - await deletePageSpeedCheckParamValidation.validateAsync(req.params); - } catch (error) { - error.status = 422; - error.service = SERVICE_NAME; - error.message = - error.details?.[0]?.message || error.message || "Validation Error"; - next(error); - return; - } - try { - return res.status(200).json({ msg: "Hit deletePageSpeedCheck" }); - } catch (error) { - error.service === undefined ? (error.service = SERVICE_NAME) : null; - error.method === undefined ? (error.method = "deletePageSpeedCheck") : null; - next(error); - } -}; - -module.exports = { - getPageSpeedChecks, - createPageSpeedCheck, - deletePageSpeedCheck, -}; diff --git a/Server/index.js b/Server/index.js index e665f21d2..25f70a532 100644 --- a/Server/index.js +++ b/Server/index.js @@ -14,7 +14,6 @@ const authRouter = require("./routes/authRoute"); const inviteRouter = require("./routes/inviteRoute"); const monitorRouter = require("./routes/monitorRoute"); const checkRouter = require("./routes/checkRoute"); -const pageSpeedCheckRouter = require("./routes/pageSpeedCheckRoute"); const maintenanceWindowRouter = require("./routes/maintenanceWindowRoute"); const { connectDbAndRunServer } = require("./configs/db"); @@ -84,7 +83,6 @@ const startApp = async () => { app.use("/api/v1/invite", inviteRouter); app.use("/api/v1/monitors", verifyJWT, monitorRouter); app.use("/api/v1/checks", verifyJWT, checkRouter); - app.use("/api/v1/pagespeed", verifyJWT, pageSpeedCheckRouter); app.use("/api/v1/maintenance-window", verifyJWT, maintenanceWindowRouter); //Temporary route for testing, remove later app.use("/api/v1/job", queueRouter); diff --git a/Server/routes/pageSpeedCheckRoute.js b/Server/routes/pageSpeedCheckRoute.js deleted file mode 100644 index 4b1de49bc..000000000 --- a/Server/routes/pageSpeedCheckRoute.js +++ /dev/null @@ -1,45 +0,0 @@ -const router = require("express").Router(); -const { verifyOwnership } = require("../middleware/verifyOwnership"); -const Monitor = require("../models/Monitor"); -const pageSpeedCheckController = require("../controllers/pageSpeedCheckController"); - -/** - * @route POST /:monitorId - * @description Create a new PageSpeedCheck for a monitor - * @access Private - * @param {string} monitorId - The ID of the monitor - * @middleware verifyOwnership - Ensures the user owns the monitor - */ -router.post( - "/:monitorId", - verifyOwnership(Monitor, "monitorId"), - pageSpeedCheckController.createPageSpeedCheck -); - -/** - * @route GET /:monitorId - * @description Get all PageSpeedChecks for a monitor - * @access Private - * @param {string} monitorId - The ID of the monitor - * @middleware verifyOwnership - Ensures the user owns the monitor - */ -router.get( - "/:monitorId", - verifyOwnership(Monitor, "monitorId"), - pageSpeedCheckController.getPageSpeedChecks -); - -/** - * @route DELETE /:monitorId - * @description Delete all PageSpeedChecks for a monitor - * @access Private - * @param {string} monitorId - The ID of the monitor - * @middleware verifyOwnership - Ensures the user owns the monitor - */ -router.delete( - "/:monitorId", - verifyOwnership(Monitor, "monitorId"), - pageSpeedCheckController.deletePageSpeedCheck -); - -module.exports = router; From 35d2d8301ec12ed63fa5e605808ecd3a4cfc761b Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Wed, 25 Sep 2024 12:11:18 +0800 Subject: [PATCH 46/98] Add maintenance window routes to docs --- Server/openapi.json | 197 ++++++++++++++++++++++++ Server/routes/maintenanceWindowRoute.js | 14 +- 2 files changed, 204 insertions(+), 7 deletions(-) diff --git a/Server/openapi.json b/Server/openapi.json index 2c5097649..a7de094f4 100644 --- a/Server/openapi.json +++ b/Server/openapi.json @@ -53,6 +53,10 @@ { "name": "maintenance-window", "description": "Maintenance window" + }, + { + "name": "queue", + "description": "Queue" } ], "paths": { @@ -1705,6 +1709,172 @@ } ] } + }, + "/maintenance-window/monitor/{monitorId}": { + "get": { + "tags": ["maintenance-window"], + "description": "Get maintenance window for monitor", + "parameters": [ + { + "name": "monitorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SuccessResponse" + } + } + } + }, + "422": { + "description": "Unprocessable Content", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "500": { + "description": "Internal Server Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + }, + "security": [ + { + "bearerAuth": [] + } + ] + }, + "post": { + "tags": ["maintenance-window"], + "description": "Create maintenance window for monitor", + "parameters": [ + { + "name": "monitorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateMaintenanceWindowBody" + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SuccessResponse" + } + } + } + }, + "422": { + "description": "Unprocessable Content", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "500": { + "description": "Internal Server Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + }, + "security": [ + { + "bearerAuth": [] + } + ] + } + }, + "/maintenance-window/user/{userId}": { + "get": { + "tags": ["maintenance-window"], + "description": "Get maintenance window for user", + "parameters": [ + { + "name": "userId", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SuccessResponse" + } + } + } + }, + "422": { + "description": "Unprocessable Content", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "500": { + "description": "Internal Server Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + }, + "security": [ + { + "bearerAuth": [] + } + ] + } } }, @@ -1878,6 +2048,33 @@ "type": "integer" } } + }, + "CreateMaintenanceWindowBody": { + "type": "object", + "required": ["userId", "active", "oneTime", "start", "end"], + "properties": { + "userId": { + "type": "string" + }, + "active": { + "type": "boolean" + }, + "oneTime": { + "type": "boolean" + }, + "start": { + "type": "string", + "format": "date-time" + }, + "end": { + "type": "string", + "format": "date-time" + }, + "expiry": { + "type": "string", + "format": "date-time" + } + } } } } diff --git a/Server/routes/maintenanceWindowRoute.js b/Server/routes/maintenanceWindowRoute.js index 876e9e668..c357df76b 100644 --- a/Server/routes/maintenanceWindowRoute.js +++ b/Server/routes/maintenanceWindowRoute.js @@ -3,8 +3,14 @@ const maintenanceWindowController = require("../controllers/maintenanceWindowCon const { verifyOwnership } = require("../middleware/verifyOwnership"); const Monitor = require("../models/Monitor"); +router.get( + "/monitor/:monitorId", + verifyOwnership(Monitor, "monitorId"), + maintenanceWindowController.getMaintenanceWindowsByMonitorId +); + router.post( - "/:monitorId", + "/monitor/:monitorId", verifyOwnership(Monitor, "monitorId"), maintenanceWindowController.createMaintenanceWindow ); @@ -14,10 +20,4 @@ router.get( maintenanceWindowController.getMaintenanceWindowsByUserId ); -router.get( - "/monitor/:monitorId", - verifyOwnership(Monitor, "monitorId"), - maintenanceWindowController.getMaintenanceWindowsByMonitorId -); - module.exports = router; From d55119c28d5ad6acc412ae4b6e6ea290c8d7808c Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Wed, 25 Sep 2024 12:55:31 +0800 Subject: [PATCH 47/98] Add job queue to docs --- Server/controllers/queueController.js | 2 +- Server/index.js | 3 +- Server/openapi.json | 170 ++++++++++++++++++++++++++ Server/routes/queueRoute.js | 4 +- Server/service/jobQueue.js | 4 +- 5 files changed, 176 insertions(+), 7 deletions(-) diff --git a/Server/controllers/queueController.js b/Server/controllers/queueController.js index 5960552c4..bbb3304ee 100644 --- a/Server/controllers/queueController.js +++ b/Server/controllers/queueController.js @@ -41,7 +41,7 @@ const addJob = async (req, res, next) => { const obliterateQueue = async (req, res, next) => { try { const obliterated = await req.jobQueue.obliterate(); - return res.status(200).send("Obliterated jobs"); + return res.status(200).send("Obliterated queue"); } catch (error) { error.service === undefined ? (error.service = SERVICE_NAME) : null; error.method === undefined ? (error.method = "obliterateQueue") : null; diff --git a/Server/index.js b/Server/index.js index 25f70a532..05c9d3059 100644 --- a/Server/index.js +++ b/Server/index.js @@ -84,8 +84,7 @@ const startApp = async () => { app.use("/api/v1/monitors", verifyJWT, monitorRouter); app.use("/api/v1/checks", verifyJWT, checkRouter); app.use("/api/v1/maintenance-window", verifyJWT, maintenanceWindowRouter); - //Temporary route for testing, remove later - app.use("/api/v1/job", queueRouter); + app.use("/api/v1/queue", verifyJWT, queueRouter); //health check app.use("/api/v1/healthy", (req, res) => { diff --git a/Server/openapi.json b/Server/openapi.json index a7de094f4..6a19bde13 100644 --- a/Server/openapi.json +++ b/Server/openapi.json @@ -1875,6 +1875,176 @@ } ] } + }, + "/queue/jobs": { + "get": { + "tags": ["queue"], + "description": "Get all jobs in queue", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SuccessResponse" + } + } + } + }, + "422": { + "description": "Unprocessable Content", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "500": { + "description": "Internal Server Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + }, + "security": [ + { + "bearerAuth": [] + } + ] + }, + "post": { + "tags": ["queue"], + "description": "Create a new job. Useful for testing scaling workers", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SuccessResponse" + } + } + } + }, + "422": { + "description": "Unprocessable Content", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "500": { + "description": "Internal Server Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + }, + "security": [ + { + "bearerAuth": [] + } + ] + } + }, + "/queue/metrics": { + "get": { + "tags": ["queue"], + "description": "Get queue metrics", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SuccessResponse" + } + } + } + }, + "422": { + "description": "Unprocessable Content", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "500": { + "description": "Internal Server Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + }, + "security": [ + { + "bearerAuth": [] + } + ] + } + }, + "/queue/obliterate": { + "post": { + "tags": ["queue"], + "description": "Obliterate job queue", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SuccessResponse" + } + } + } + }, + "422": { + "description": "Unprocessable Content", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "500": { + "description": "Internal Server Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + }, + "security": [ + { + "bearerAuth": [] + } + ] + } } }, diff --git a/Server/routes/queueRoute.js b/Server/routes/queueRoute.js index cbc68df6d..b14eaa2b0 100644 --- a/Server/routes/queueRoute.js +++ b/Server/routes/queueRoute.js @@ -4,10 +4,10 @@ const queueController = require("../controllers/queueController"); router.get("/metrics", queueController.getMetrics); // Get Jobs -router.get("/", queueController.getJobs); +router.get("/jobs", queueController.getJobs); // Add Job -router.post("/", queueController.addJob); +router.post("/jobs", queueController.addJob); // Obliterate Queue router.post("/obliterate", queueController.obliterateQueue); diff --git a/Server/service/jobQueue.js b/Server/service/jobQueue.js index 5d58dd4a4..5a6d3e8e0 100644 --- a/Server/service/jobQueue.js +++ b/Server/service/jobQueue.js @@ -240,12 +240,12 @@ class JobQueue { */ async addJob(jobName, payload) { try { - console.log("Adding job", payload.url); + console.log("Adding job", payload?.url ?? "No URL"); // Execute job immediately await this.queue.add(jobName, payload); await this.queue.add(jobName, payload, { repeat: { - every: payload.interval, + every: payload?.interval ?? 60000, }, }); const workerStats = await this.getWorkerStats(); From 825777c2a8bfe868f1c243830c6e2cbec2ec3667 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Wed, 25 Sep 2024 13:03:03 +0800 Subject: [PATCH 48/98] Update nginx conf for api docs --- Docker/nginx/conf.d/default.conf | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/Docker/nginx/conf.d/default.conf b/Docker/nginx/conf.d/default.conf index a04d32c87..a27e8a744 100644 --- a/Docker/nginx/conf.d/default.conf +++ b/Docker/nginx/conf.d/default.conf @@ -23,6 +23,15 @@ server { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } + + location /api-doc/ { + proxy_pass http://server:5000/api-doc/; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + } } server { @@ -48,4 +57,13 @@ server { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } + + location /api-doc/ { + proxy_pass http://server:5000/api-doc/; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + } } From 06057671b424a224ff8b2f0b955f525ba97281d5 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Wed, 25 Sep 2024 13:16:27 +0800 Subject: [PATCH 49/98] Add swagger-ui dependency --- Server/package-lock.json | 22 ++++++++++++++++++++++ Server/package.json | 1 + 2 files changed, 23 insertions(+) diff --git a/Server/package-lock.json b/Server/package-lock.json index d2ad88cff..0d7821c5b 100644 --- a/Server/package-lock.json +++ b/Server/package-lock.json @@ -28,6 +28,7 @@ "ping": "0.4.4", "sharp": "0.33.4", "ssl-checker": "2.0.10", + "swagger-ui-express": "5.0.1", "winston": "^3.13.0" }, "devDependencies": { @@ -5178,6 +5179,27 @@ "node": ">= 10" } }, + "node_modules/swagger-ui-dist": { + "version": "5.17.14", + "resolved": "https://registry.npmjs.org/swagger-ui-dist/-/swagger-ui-dist-5.17.14.tgz", + "integrity": "sha512-CVbSfaLpstV65OnSjbXfVd6Sta3q3F7Cj/yYuvHMp1P90LztOLs6PfUnKEVAeiIVQt9u2SaPwv0LiH/OyMjHRw==", + "license": "Apache-2.0" + }, + "node_modules/swagger-ui-express": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/swagger-ui-express/-/swagger-ui-express-5.0.1.tgz", + "integrity": "sha512-SrNU3RiBGTLLmFU8GIJdOdanJTl4TOmT27tt3bWWHppqYmAZ6IDuEuBvMU6nZq0zLEe6b/1rACXCgLZqO6ZfrA==", + "license": "MIT", + "dependencies": { + "swagger-ui-dist": ">=5.0.0" + }, + "engines": { + "node": ">= v0.10.32" + }, + "peerDependencies": { + "express": ">=4.0.0 || >=5.0.0-beta" + } + }, "node_modules/tar": { "version": "6.2.1", "resolved": "https://registry.npmjs.org/tar/-/tar-6.2.1.tgz", diff --git a/Server/package.json b/Server/package.json index 6c383ce73..75d3b1cc2 100644 --- a/Server/package.json +++ b/Server/package.json @@ -30,6 +30,7 @@ "ping": "0.4.4", "sharp": "0.33.4", "ssl-checker": "2.0.10", + "swagger-ui-express": "5.0.1", "winston": "^3.13.0" }, "devDependencies": { From 5c4174d3ac31faedd395c7f046e6df3668fa876b Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Wed, 25 Sep 2024 13:36:35 +0800 Subject: [PATCH 50/98] Add bluewave server to swagger config --- Docker/nginx/conf.d/default.conf | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Docker/nginx/conf.d/default.conf b/Docker/nginx/conf.d/default.conf index a27e8a744..5f37d48b7 100644 --- a/Docker/nginx/conf.d/default.conf +++ b/Docker/nginx/conf.d/default.conf @@ -24,8 +24,8 @@ server { proxy_set_header X-Forwarded-Proto $scheme; } - location /api-doc/ { - proxy_pass http://server:5000/api-doc/; + location /api-docs/ { + proxy_pass http://server:5000/api-docs/; proxy_http_version 1.1; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; @@ -58,8 +58,8 @@ server { proxy_set_header X-Forwarded-Proto $scheme; } - location /api-doc/ { - proxy_pass http://server:5000/api-doc/; + location /api-docs/ { + proxy_pass http://server:5000/api-docs/; proxy_http_version 1.1; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; From 7996210852bd080a93951e4871d77be9031cfe26 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Wed, 25 Sep 2024 13:41:19 +0800 Subject: [PATCH 51/98] Add corrected bluewave server to swagger docs --- Server/openapi.json | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/Server/openapi.json b/Server/openapi.json index 6a19bde13..a206742f6 100644 --- a/Server/openapi.json +++ b/Server/openapi.json @@ -22,12 +22,28 @@ "variables": { "PORT": { "description": "API Port", - "enum": ["5000", "3000", "8080"], + "enum": ["5000"], "default": "5000" }, "API_PATH": { "description": "API Base Path", - "enum": ["api/v1", "api/v1.1", "api/v2"], + "enum": ["api/v1"], + "default": "api/v1" + } + } + }, + { + "url": "https://uptime-demo.bluewavelabs.ca:/{API_PATH}", + "description": "Bluewave Demo Server", + "variables": { + "PORT": { + "description": "API Port", + "enum": ["5000"], + "default": "5000" + }, + "API_PATH": { + "description": "API Base Path", + "enum": ["api/v1"], "default": "api/v1" } } From e2df0e7c6c8cdab4db95184018580017dbfa7ba4 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Wed, 25 Sep 2024 13:46:55 +0800 Subject: [PATCH 52/98] Fix typo --- Server/openapi.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Server/openapi.json b/Server/openapi.json index a206742f6..ae4f7798f 100644 --- a/Server/openapi.json +++ b/Server/openapi.json @@ -33,7 +33,7 @@ } }, { - "url": "https://uptime-demo.bluewavelabs.ca:/{API_PATH}", + "url": "https://uptime-demo.bluewavelabs.ca/{API_PATH}", "description": "Bluewave Demo Server", "variables": { "PORT": { From 4e8675df459bfe4a46345cf5c0c7715a5fa38a22 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Wed, 25 Sep 2024 14:07:33 +0800 Subject: [PATCH 53/98] Remove API endpoints from docs, link to swagger docs --- README.md | 1856 +---------------------------------------------------- 1 file changed, 5 insertions(+), 1851 deletions(-) diff --git a/README.md b/README.md index 3c96a0af4..28851a0f4 100644 --- a/README.md +++ b/README.md @@ -90,45 +90,7 @@ Also check other developer and contributor-friendly projects of BlueWave: - [Database](#databases) - [(Optional) Dockerised Databases](#optional-docker-databases) - [Start Server](#start-server) -1. [Endpoints](#endpoints) - ###### Auth - - POST [/api/v1/auth/register](#post-register) - - POST [/api/v1/auth/login](#post-login) - - PUT [/api/v1/auth/user/{userId}](#post-auth-user-edit-id) - - GET [/api/v1/auth/users](#get-all-users-id) - - GET [/api/v1/auth/users/admin](#get-all-admin-users-id) - - POST [/api/v1/auth/invite](#post-auth-invite-id) - - POST [/api/v1/auth/invite/verify/](#post-auth-invite-verify-id) - - POST [/api/v1/auth/recovery/request](#post-auth-recovery-request-id) - - POST [/api/v1/auth/recovery/validate](#post-auth-recovery-validate-id) - - POST [/api/v1/auth/recovery/reset](#post-auth-recovery-reset-id) - ###### Monitors - - GET [/api/v1/monitors](#get-monitors) - - GET [/api/v1/monitors/{monitorId}](#get-monitor-id) - - GET [/api/v1/monitors/user/{userId}?limit](#get-monitors-user-userid) - - POST [/api/v1/monitors](#post-monitors) - - PUT [/api/v1/monitors/{monitorId}](#put-monitors-id) - - DELETE [/api/v1/monitors/{monitorId}](#delete-monitors-id) - - DELETE [/api/v1/monitors/all](#delete-all-monitors) - ###### Checks - - POST [/api/v1/checks/{monitorId}](#post-checks) - - GET [/api/v1/checks/{monitorId}](#get-checks) - - DELETE [/api/v1/checks/{monitorId}](#delete-checks) - ###### Alerts - - POST [/api/v1/alerts/{monitorId}](#create-alert) - - GET [/api/v1/alerts/user/{userId}](#get-alerts-user-id) - - GET [/api/v1/alerts/monitor/{monitorId}](#get-alerts-monitor-id) - - GET [/api/v1/alerts/{alertId}](#get-alert-alert-id) - - PUT [/api/v1/alerts/{alertId}](#edit-alert) - - DELETE [/api/v1/alerts/{alertId}](#delete-alert) - ###### Page Speed - - POST [/api/v1/pagespeed/:monitorId](#post-pagespeed) - - GET [/api/v1/pagespeed/:monitorId](#get-pagespeed) - - DELETE [/api/v1/pagespeed/:monitorId](#delete-pagespeed) - ###### Maintenance Window - - POST [/api/v1/maintenance-window/:monitorId](#post-maintenance-window) - - GET [/api/v1/maintenance-window/user/:userId](#get-maintenance-window-by-userid) - - GET [/api/v1/maintenance-window/monitor/:monitorId](#get-maintenance-window-by-monitor-id) +1. [API Documentation](#api-documentation) 1. [Error Handling](#error-handling) 1. [Contributors](#contributors) @@ -332,1821 +294,13 @@ OR --- -#### Endpoints +#### API Documentation -All endpoints return a response in this format: +Our API is documented in accordance with the [OpenAPI spec](https://www.openapis.org/). -| Name | Type | Notes | -| ------- | --------- | ----------------------------- | -| success | `boolean` | Success or failure of request | -| msg | `string` | Message describing response | -| data | `Object` | Arbitrary Payload | +You can see the documentation on your local development server at [http://localhost:{port}/api-docs](http://localhost:5000/api-docs) -Example: - -``` -{success: true, msg: "Successful Request", data: {test: testData}} -``` - ---- - -##### Data Types - -
    -User - -| Name | Type | Notes | -| ------------- | --------- | --------------------- | -| firstname | `string` | First name | -| lastname | `string` | Last name | -| email | `string` | User's email | -| profilePicUrl | `string` | URL to User's picture | -| isActive | `boolean` | Default to `true` | -| isVerified | `boolean` | Default to `false` | -| updated_at | `Date` | Last update time | -| created_at | `Date` | Time created at | - -
    - -
    -Monitor - -| Name | Type | Notes | -| ----------- | --------- | ---------------------------------------- | -| userId | `string` | Unique ID identifying monitor creator | -| name | `string` | Name of the monitor | -| description | `string` | Description of the monitor | -| url | `string` | Url the monitor will ping | -| isActive | `boolean` | Whether or not the monitor is active | -| interval | `integer` | Interval with which to ping monitor (ms) | -| updatedAt | `Date` | Last time the monitor was updated | -| CreatedAt | `Date` | When the monitor was updated | - -
    - -
    -Check - -| Name | Type | Notes | -| ------------ | --------- | ----------------------------------------------- | -| monitorId | `string` | Unique ID for the monitor | -| status | `boolean` | Indicates the service is Up or Down | -| responseTime | `integer` | Indicates the response time of the service (ms) | -| statusCode | `integer` | Status Code returned from the service | -| message | `string` | Message returned from the service | -| updatedAt | `Date` | Last time the check was updated | -| CreatedAt | `Date` | When the check was created | - -
    - -
    -Alert - -| Name | Type | Notes | -| ----------------- | --------- | ------------------------------------------------- | -| checkId | `string` | Unique ID for the associated check | -| monitorId | `string` | Unique ID for the associated monitor | -| userId | `string` | Unique ID for the associated user | -| status | `boolean` | Indicates the service is Up or Down | -| message | `string` | Message for the user about the down service | -| notifiedStatus | `boolean` | Indicates whether the user is notified | -| acknowledgeStatus | `boolean` | Indicates whether the user acknowledged the alert | -| updatedAt | `Date` | Last time the alert was updated | -| CreatedAt | `Date` | When the alert was created | - -
    - ---- - -###### Auth - -
    -POST /api/v1/auth/register - -##### Method/Headers - -> | Method/Headers | Value | -> | -------------- | ------------------- | -> | Method | POST | -> | content-type | multipart/form-data | - -##### Form - -> | Name | Type | Notes | -> | --------- | --------------- | ----------------------------------------------- | -> | firstName | `string` | | -> | lastName | `string` | | -> | email | `string` | Valid email address | -> | password | `string` | Min 8 chars, One Upper, one number, one special | -> | role | `Array` | Array of user roles | - -##### Response Payload - -> | Type | Notes | -> | ---- | -------------- | -> | User | User data | -> | JWT | JSON web token | - -##### Sample CURL request - -``` -curl --request POST \ - --url http://localhost:5000/api/v1/auth/register \ - --header 'Content-Type: multipart/form-data' \ - --form firstName=Alex \ - --form lastName=Hollidaty \ - --form email=ajhollid@gmail.com \ - --form 'password=Testtest1!' \ - --form 'role[]=admin' -``` - -##### Sample Response - -```json -{ - "success": true, - "msg": "User created successfully", - "data": { - "user": { - "_id": "66a1425b873da2207443f192", - "firstName": "First Name", - "lastName": "Last Name", - "email": "name@gmail.com", - "isActive": true, - "isVerified": false, - "role": ["admin"], - "createdAt": "2024-07-24T18:05:15.852Z", - "updatedAt": "2024-07-24T18:05:15.852Z", - "__v": 0 - }, - "token": "" - } -} -``` - -
    - -
    -POST /api/v1/auth/login - -##### Method/Headers - -> | Method/Headers | Value | -> | -------------- | ---------------- | -> | Method | POST | -> | content-type | application/json | - -##### Body - -> | Name | Type | Notes | -> | -------- | -------- | ------------------- | -> | email | `string` | Valid email address | -> | password | `string` | | - -##### Response Payload - -> | Type | Notes | -> | ---- | -------------- | -> | User | User data | -> | JWT | JSON web token | - -##### Sample CURL request - -``` -curl --request POST \ - --url http://localhost:5000/api/v1/auth/login \ - --header 'Authorization: Bearer undefined' \ - --header 'Content-Type: application/json' \ - --data '{ - "email" : "name@gmail.com", - "password": "Testtest1!" -}' -``` - -##### Sample response - -```json -{ -{ - "success": true, - "msg": "User logged in successfully", - "data": { - "user": { - "_id": "66a1425b873da2207443f192", - "firstName": "First Name", - "lastName": "Last Name", - "email": "name@gmail.com", - "isActive": true, - "isVerified": false, - "role": ["admin"], - "createdAt": "2024-07-24T18:05:15.852Z", - "updatedAt": "2024-07-24T18:05:15.852Z", - "__v": 0 - }, - "token": "" - } -} -} -``` - -
    - -
    -POST/api/v1/auth/user/{userId} - -###### Method/Headers - -> | Method/Headers | Value | -> | -------------- | ------------------- | -> | Method | POST | -> | content-type | multipart/form-data | - -##### Form - -> | Name | Type | Notes | -> | ----------- | -------- | --------------------------- | -> | firstName | `string` | Optional | -> | lastName | `string` | Optional | -> | profileIame | `file` | Optional | -> | password | `string` | Required to change password | -> | newPassword | `string` | Required to change password | - -###### Response Payload - -> | Type | Notes | -> | ------ | ------------------------ | -> | `User` | Returns the updated user | - -##### Sample CURL request - -``` -curl --request POST \ - --url http://localhost:5000/api/v1/auth/user/66a1425b873da2207443f192 \ - --header 'Authorization: ' \ - --header 'Content-Type: multipart/form-data' \ - --form firstName=Test \ - --form lastName=Test \ - --form profileImage=@/home/user/Desktop/cat.jpg \ - --form 'newPassword=Testtest1!' \ - --form 'password=Testtest2!' -``` - -###### Sample Response - -```json -{ - "success": true, - "msg": "User updated successfully", - "data": { - "_id": "66a1425b873da2207443f192", - "firstName": "First name", - "lastName": "Last name", - "email": "name@gmail.com", - "isActive": true, - "isVerified": false, - "role": ["admin"], - "createdAt": "2024-07-24T18:05:15.852Z", - "updatedAt": "2024-07-24T18:31:32.314Z", - "__v": 0, - "avatarImage": "" - } -} -``` - -
    - -
    -GET/api/v1/auth/users - -###### Method/Headers - -> | Method/Headers | Value | -> | -------------- | ---------------- | -> | Method | GET | -> | content-type | application/json | - -###### Response Payload - -> | Type | Notes | -> | ------------- | ------------------------------------- | -> | `Array` | Returns an array containing all users | - -##### Sample CURL request - -``` -curl --request GET \ - --url http://localhost:5000/api/v1/auth/users \ - --header 'Authorization: \ -``` - -##### Sample Resonse - -```json -{ - "success": true, - "msg": "Got all users", - "data": [ - { - "_id": "669e90072d5663d25808bc7b", - "firstName": "First name", - "lastName": "Last name", - "email": "name@gmail.com", - "isActive": true, - "isVerified": false, - "role": ["admin"], - "createdAt": "2024-07-22T16:59:51.695Z", - "updatedAt": "2024-07-22T16:59:51.695Z", - "__v": 0 - } - ] -} -``` - -
    - -
    -POST/api/v1/auth/recovery/request - -###### Method/Headers - -> | Method/Headers | Value | -> | -------------- | ---------------- | -> | Method | POST | -> | content-type | application/json | - -##### Body - -> | Name | Type | Notes | -> | ----- | -------- | ------------ | -> | email | `string` | User's email | - -###### Response Payload - -> | Type | Notes | -> | --------------- | --------------------------------------- | -> | `RecoveryToken` | Returns a recovery token if email found | - -##### Sample CURL request - -``` -curl --request POST \ - --url http://localhost:5000/api/v1/auth/recovery/request \ - --header 'Content-Type: application/json' \ - --data '{ - "email" : "name@gmail.com" -}' -``` - -###### Sample Response - -```json -{ - "success": true, - "msg": "Created recovery token", - "data": { - "email": "name@gmail.com", - "token": "f519da5e4a9be40cfc3c0fde97e60c0e6d17bdaa613f5ba537a45073f3865193", - "_id": "6668878263587f30748e968e", - "expiry": "2024-06-11T17:21:06.984Z", - "createdAt": "2024-06-11T17:21:06.985Z", - "updatedAt": "2024-06-11T17:21:06.985Z", - "__v": 0 - } -} -``` - -
    - -
    -POST/api/v1/auth/recovery/validate - -###### Method/Headers - -> | Method/Headers | Value | -> | -------------- | ---------------- | -> | Method | POST | -> | content-type | application/json | - -##### Body - -> | Name | Type | Notes | -> | ------------- | -------- | ----------------------------------- | -> | recoveryToken | `string` | Token issued in `/recovery/request` | - -###### Response Payload - -> | Type | Notes | -> | --------------- | -------------------------- | -> | `RecoveryToken` | Returns the recovery token | - -##### Sample CURL request - -``` -curl --request POST \ - --url http://localhost:5000/api/v1/auth/recovery/validate \ - --header 'Content-Type: application/json' \ - --data '{ - "recoveryToken" : "f519da5e4a9be40cfc3c0fde97e60c0e6d17bdaa613f5ba537a45073f3865193" -}' -``` - -###### Sample Response - -```json -{ - "success": true, - "msg": "Token is valid", - "data": { - "_id": "6668894263587f30748e969a", - "email": "name@gmail.com", - "token": "457d9926b24dedf613f120eeb524ef00ac45b3f0fc5c70bd25b1cc8aa83a64a0", - "expiry": "2024-06-11T17:28:34.349Z", - "createdAt": "2024-06-11T17:28:34.349Z", - "updatedAt": "2024-06-11T17:28:34.349Z", - "__v": 0 - } -} -``` - -
    - -
    -POST/api/v1/auth/recovery/reset - -###### Method/Headers - -> | Method/Headers | Value | -> | -------------- | ---------------- | -> | Method | POST | -> | content-type | application/json | - -##### Body - -> | Name | Type | Notes | -> | ------------- | -------- | --------------------------------------------- | -> | recoveryToken | `string` | Token issued returned by `/recovery/validate` | -> | password | `string` | User's new password` | - -###### Response Payload - -> | Type | Notes | -> | ------ | ------------------------ | -> | `User` | Returns the updated user | - -##### Sample CURL request - -``` -curl --request POST \ - --url http://localhost:5000/api/v1/auth/recovery/reset \ - --header 'Content-Type: application/json' \ - --data '{ - "recoveryToken" : "f519da5e4a9be40cfc3c0fde97e60c0e6d17bdaa613f5ba537a45073f3865193", - "password": "testtest" -}' -``` - -###### Sample Response - -```json -{ - "success": true, - "msg": "Password reset", - "data": { - "_id": "66675891cb17336d84c25d9f", - "firstname": "First Name", - "lastname": "Last Name", - "email": "name@gmail.com", - "isActive": true, - "isVerified": false, - "createdAt": "2024-06-10T19:48:33.863Z", - "updatedAt": "2024-06-11T17:21:22.289Z", - "__v": 0 - } -} -``` - -
    - ---- - -###### Monitors - -
    -GET /api/v1/monitors - -##### Method/Headers - -> | Method/Headers | Value | -> | -------------- | ---------------- | -> | Method | GET | -> | content-type | application/json | - -##### Response Payload - -> | Type | Notes | -> | ---------------- | --------------------- | -> | `Array` | Array of all monitors | - -###### Sample cURL Request - -``` -curl --request GET \ - --url http://localhost:5000/api/v1/monitors \ - --header '' \ -``` - -###### Sample Response - -```json -{ - "success": true, - "msg": "Monitors found", - "data": [ - { - "_id": "664d070786e62625ac612ca1", - "userId": "6645079aae0b439371913972", - "name": "Wha3", - "description": "Description", - "url": "https://monitor0.com", - "isActive": true, - "interval": 60000, - "createdAt": "2024-05-21T20:41:43.051Z", - "updatedAt": "2024-05-21T20:45:10.496Z", - "__v": 0 - }, - { - "_id": "664e5ccf189c864800debc16", - "userId": "6645079aae0b439371913972", - "name": "Inserting a new Monitor", - "description": "Description", - "url": "https://monitor0.com", - "isActive": true, - "interval": 60000, - "createdAt": "2024-05-22T20:59:59.295Z", - "updatedAt": "2024-05-22T20:59:59.295Z", - "__v": 0 - } - ] -} -``` - -
    - -
    -GET /api/v1/monitor/{id}?status - -###### Method/Headers - -> | Method/Headers | Value | -> | -------------- | ---------------- | -> | Method | GET | -> | content-type | application/json | - -###### Query Params - -> | Name | Type | Required | Notes | -> | --------- | --------- | -------- | ------------------------------------------------ | -> | status | `boolean` | Optional | Check status | -> | limit | `number` | Optional | Number of checks to return | -> | sortOrder | `string` | Optional | `desc`:Newest -> Oldest, `asc`: Oldest -> Newest | - -###### Response Payload - -> | Type | Notes | -> | --------- | --------------------------------------------------- | -> | `Monitor` | Single monitor with the id in the request parameter | - -###### Sample cURL Request - -``` -curl --request GET \ - --url http://localhost:5000/api/v1/monitors/664d070786e62625ac612ca1?status=true?limit=0 \ - --header '' \ -``` - -###### Sample Response - -```json -{ - "success": true, - "msg": "Got monitor by Id successfully", - "data": { - "_id": "6671eb54f7040ece47892f53", - "userId": "666c9146c9bfa20db790b1df", - "name": "Google Monitor", - "description": "Google", - "type": "http", - "url": "https://www.google.com/404", - "isActive": true, - "interval": 10000, - "createdAt": "2024-06-18T20:17:24.112Z", - "updatedAt": "2024-06-18T20:17:24.112Z", - "__v": 0, - "checks": [ - { - "_id": "6671eb5af7040ece47892f61", - "monitorId": "6671eb54f7040ece47892f53", - "status": false, - "responseTime": 145, - "expiry": "2024-06-18T20:17:30.246Z", - "statusCode": 404, - "createdAt": "2024-06-18T20:17:30.246Z", - "updatedAt": "2024-06-18T20:17:30.246Z", - "__v": 0 - }, - { - "_id": "6671eb64f7040ece47892f6b", - "monitorId": "6671eb54f7040ece47892f53", - "status": false, - "responseTime": 170, - "expiry": "2024-06-18T20:17:40.209Z", - "statusCode": 404, - "createdAt": "2024-06-18T20:17:40.210Z", - "updatedAt": "2024-06-18T20:17:40.210Z", - "__v": 0 - } - ] - } -} -``` - -
    - -
    -GET /api/v1/monitors/user/{userId}?limit - -###### Method/Headers - -> | Method/Headers | Value | -> | -------------- | ---------------- | -> | Method | GET | -> | content-type | application/json | - -###### Query Params - -> | Name | Type | Required | Notes | -> | --------- | --------- | -------- | ------------------------------------------------- | -> | status | `boolean` | Optional | Check status | -> | type | `string` | Optional | Multiple allowed: `http` \| `ping` \| `pagespeed` | -> | limit | `number` | Optional | Monitor status | -> | sortOrder | `string` | Optional | `desc`:Newest -> Oldest, `asc`: Oldest -> Newest | - -###### Response Payload - -> | Type | Notes | -> | ---------------- | ------------------------------------------------------- | -> | `Array` | Array of monitors created by user with specified UserID | - -###### Sample cURL Request - -``` -curl --request GET \ - --url http://localhost:5000/api/v1/monitors/user/6645079aae0b439371913972?limit=25 \ - --header '' \ -``` - -###### Sample Response - -```json -{ - "success": true, - "msg": "Got monitor for 666c9146c9bfa20db790b1df successfully\"", - "data": [ - { - "_id": "6671eb54f7040ece47892f53", - "userId": "666c9146c9bfa20db790b1df", - "name": "Google Monitor", - "description": "Google", - "type": "http", - "url": "https://www.google.com/404", - "isActive": true, - "interval": 10000, - "createdAt": "2024-06-18T20:17:24.112Z", - "updatedAt": "2024-06-18T20:17:24.112Z", - "__v": 0, - "checks": [ - { - "_id": "6671eb5af7040ece47892f61", - "monitorId": "6671eb54f7040ece47892f53", - "status": false, - "responseTime": 145, - "expiry": "2024-06-18T20:17:30.246Z", - "statusCode": 404, - "createdAt": "2024-06-18T20:17:30.246Z", - "updatedAt": "2024-06-18T20:17:30.246Z", - "__v": 0 - } - ] - } - ] -} -``` - -
    - -
    -POST/api/v1/monitors - -###### Method/Headers - -> | Method/Headers | Value | -> | -------------- | ---------------- | -> | Method | POST | -> | content-type | application/json | - -##### Body - -> | Name | Type | Notes | Accepted Values | -> | ----------- | --------- | ---------------------- | --------------------------------------- | -> | userId | `string` | UserId of current user | | -> | name | `string` | Monitor name | | -> | description | `string` | Monitor Description | | -> | type | `string` | Valid email address | `"ping"`|`"http"`|`pagespeed` | -> | url | `string` | URL of service or IP | | -> | isActive | `boolean` | | | -> | interval | `number` | In ms | | - -###### Response Payload - -> | Type | Notes | -> | --------- | ------------------------------- | -> | `Monitor` | Returns newly created `Monitor` | - -##### Sample CURL request - -``` -curl --request POST \ - --url http://localhost:5000/api/v1/monitors \ - --header \ - --header 'Content-Type: application/json' \ - --data '{ - "userId": "66675891cb17336d84c25d9f", - "name": "Ping Google", - "description": "Google", - "type": "ping", - "url": "8.8.8.8", - "isActive": true, - "interval": 5000}' -``` - -##### Sample Response - -```json -{ - "success": true, - "msg": "Monitor created", - "data": { - "userId": "6645079aae0b439371913972", - "name": "Inserting a new Monitor", - "description": "Description", - "url": "https://monitor0.com", - "isActive": true, - "interval": 60000, - "_id": "664e5ccf189c864800debc16", - "createdAt": "2024-05-22T20:59:59.295Z", - "updatedAt": "2024-05-22T20:59:59.295Z", - "__v": 0 - } -} -``` - -
    - -
    -POST/api/v1/monitors/delete/{monitorId} - -###### Method/Headers - -> | Method/Headers | Value | -> | -------------- | ---------------- | -> | Method | POST | -> | content-type | application/json | - -###### Response Payload - -> | Type | Notes | -> | ---- | ------------------- | -> | None | No payload returned | - -###### Sample CURL request - -``` -curl --request POST \ - --url http://localhost:5000/api/v1/monitors/delete/664e632a7a3ee9d620761938 \ - --header '' \ - --header 'Content-Type: application/json' \ -``` - -###### Sample Response - -```json -{ - "success": true, - "msg": "Monitor deleted" -} -``` - -##
    - -
    -POST/api/v1/monitors/edit/{monitorId} - -###### Method/Headers - -> | Method/Headers | Value | -> | -------------- | ---------------- | -> | Method | POST | -> | content-type | application/json | - -##### Body - -> | Name | Type | Notes | Accepted Values | -> | ----------- | -------- | ------------------- | --------------- | -> | name | `string` | Monitor name | | -> | description | `string` | Monitor Description | | -> | interval | `number` | In ms | - -###### Response Payload - -> | Type | Notes | -> | --------- | --------------------------- | -> | `Monitor` | Returns the updated monitor | - -##### Sample CURL request - -``` -curl --request POST \ - --url http://localhost:5000/api/v1/monitors/edit/664e5ccf189c864800debc16 \ - --header ' - ---- - -###### Checks - -
    -POST/api/v1/checks/{monitorId} - -###### Method/Headers - -> | Method/Headers | Value | -> | -------------- | ----- | -> | Method | POST | - -###### Response Payload - -> | Type | Notes | -> | ------- | --------------------------- | -> | `Check` | Returns newly created check | - -###### Body - -> | Name | Type | Notes | -> | ------------ | --------- | -------------------------------------- | -> | monitorId | `string` | Monitor associated with Check | -> | status | `boolean` | `true` for up and `false` for down | -> | responseTime | `number` | How long it took the server to respond | -> | statusCode | `number` | HTTP Status code of response | -> | message | `string` | | - -##### Sample CURL request - -``` -curl --request POST \ - --url http://localhost:5000/api/v1/checks/66562414035c4ce6a8a610ac \ - --header 'Authorization: ' \ - --header 'Content-Type: application/json' \ - --data '{ - "monitorId": "66562414035c4ce6a8a610ac", - "status": true, - "responseTime": 1, - "statusCode": 200, - "message": "good" -}' -``` - -###### Sample Response - -```json -{ - "success": true, - "msg": "Check created", - "data": { - "monitorId": "66562414035c4ce6a8a610ac", - "status": true, - "responseTime": 1, - "statusCode": 200, - "message": "good", - "_id": "66576decba9f70148ea1f354", - "createdAt": "2024-05-29T18:03:24.445Z", - "updatedAt": "2024-05-29T18:03:24.445Z", - "__v": 0 - } -} -``` - -
    - -
    -GET/api/v1/checks/{monitorId} - -###### Method/Headers - -> | Method/Headers | Value | -> | -------------- | ----- | -> | Method | GET | - -###### Response Payload - -> | Type | Notes | -> | --------------- | ------------------------ | -> | `Array` | Array of `Check` objects | - -##### Sample CURL request - -``` -curl --request GET \ - --url http://localhost:5000/api/v1/checks/66562414035c4ce6a8a610ac \ - --header 'Authorization: ' \ -``` - -###### Sample Response - -```json -{ - "success": true, - "msg": "Checks retrieved", - "data": [ - { - "_id": "66576c0194e11c0d4409d3c1", - "monitorId": "66562414035c4ce6a8a610ac", - "status": true, - "responseTime": 1, - "statusCode": 200, - "message": "good", - "createdAt": "2024-05-29T17:55:13.581Z", - "updatedAt": "2024-05-29T17:55:13.581Z", - "__v": 0 - }, - { - "_id": "66576c0994e11c0d4409d3c5", - "monitorId": "66562414035c4ce6a8a610ac", - "status": true, - "responseTime": 2, - "statusCode": 200, - "message": "good", - "createdAt": "2024-05-29T17:55:21.127Z", - "updatedAt": "2024-05-29T17:55:21.127Z", - "__v": 0 - } - ] -} -``` - -
    - -
    -POST/api/v1/checks/delete/{monitorId} - -###### Method/Headers - -> | Method/Headers | Value | -> | -------------- | ----- | -> | Method | POST | - -###### Response Payload - -> | Type | Notes | -> | -------- | -------------------------------------------------------------------- | -> | `Object` | `{deletedCount: n}` Returns an object showing how many items deleted | - -##### Sample CURL request - -``` -curl --request POST \ - --url http://localhost:5000/api/v1/checks/delete/66562414035c4ce6a8a610ac \ - --header 'Authorization: ' \ -``` - -###### Sample Response - -```json -{ - "success": true, - "msg": "Checks deleted", - "data": { - "deletedCount": 3 - } -} -``` - -
    - ---- - -###### Alerts - -
    -POST/api/v1/alerts/{monitorId} - -###### Method/Headers - -> | Method/Headers | Value | -> | -------------- | ----- | -> | Method | POST | - -###### Response Payload - -> | Type | Notes | -> | ------- | ----------------------------- | -> | `Alert` | Returns newly created `Alert` | - -###### Body - - "checkId": "66577a3fd16dcf7c1ce35148", - "monitorId": "6657789ebf6766ee8e2d2edb", - "userId": "6654d1a2634754f789e1f115", - "status": false, - "message": "This is a test alert", - "notifiedStatus": "false", - "acknowledgeStatus": false - -> | Name | Type | Notes | -> | ----------------- | --------- | --------------------------------------- | -> | checkId | `string` | Id of `Check` associated with `Alert` | -> | monitorId | `string` | Id of `Monitor` associated with `Alert` | -> | userId | `string` | Id of `User` associated with `Alert` | -> | status | `boolean` | Status of `Alert` | -> | message | `string` | `Alert` message | -> | notifiedStatus | `boolean` | | -> | acknowledgeStatus | `boolean` | | - -##### Sample CURL request - -``` - -``` - -###### Sample Response - -```json - -``` - -
    - -
    -GET/api/v1/alerts/user/{userId} - -###### Method/Headers - -> | Method/Headers | Value | -> | -------------- | ----- | -> | Method | GET | - -###### Response Payload - -> | Type | Notes | -> | -------------- | --------------------------------------- | -> | `Array` | Returns all `Alert` created by a `User` | - -##### Sample CURL request - -``` -curl --request GET \ - --url http://localhost:5000/api/v1/alerts/user/6654d1a2634754f789e1f115 \ - --header 'Authorization: ' -``` - -###### Sample Response - -```json -{ - "success": true, - "msg": "Got alerts", - "data": [ - { - "_id": "6657813d809adfded891a6b7", - "checkId": "66577a3fd16dcf7c1ce35148", - "monitorId": "6657789ebf6766ee8e2d2edb", - "userId": "6654d1a2634754f789e1f115", - "status": false, - "message": "This is a test alert", - "notifiedStatus": false, - "acknowledgeStatus": false, - "createdAt": "2024-05-29T19:25:49.317Z", - "updatedAt": "2024-05-29T19:25:49.317Z", - "__v": 0 - } - ] -} -``` - -
    -
    -GET/api/v1/alerts/monitor/{monitorId} - -###### Method/Headers - -> | Method/Headers | Value | -> | -------------- | ----- | -> | Method | GET | - -###### Response Payload - -> | Type | Notes | -> | -------------- | -------------------------------------------------------------- | -> | `Array` | Returns an array of `Alert` belonging to a specified `Monitor` | - -##### Sample CURL request - -``` -curl --request GET \ - --url http://localhost:5000/api/v1/alerts/monitor/6657789ebf6766ee8e2d2edb \ - --header 'Authorization: ' \ -``` - -###### Sample Response - -```json -{ - "success": true, - "msg": "Got alerts by Monitor", - "data": [ - { - "_id": "6657813d809adfded891a6b7", - "checkId": "66577a3fd16dcf7c1ce35148", - "monitorId": "6657789ebf6766ee8e2d2edb", - "userId": "6654d1a2634754f789e1f115", - "status": false, - "message": "This is a test alert", - "notifiedStatus": false, - "acknowledgeStatus": false, - "createdAt": "2024-05-29T19:25:49.317Z", - "updatedAt": "2024-05-29T19:25:49.317Z", - "__v": 0 - } - ] -} -``` - -
    - -
    -GET/api/v1/alerts/{alertId} - -###### Method/Headers - -> | Method/Headers | Value | -> | -------------- | ----- | -> | Method | GET | - -###### Response Payload - -> | Type | Notes | -> | ------- | ------------------------- | -> | `Alert` | Returns specified `Alert` | - -##### Sample CURL request - -``` -curl --request GET \ - --url http://localhost:5000/api/v1/alerts/66577ddae5ff3c91437d0887 \ - --header 'Authorization: ' \ -``` - -###### Sample Response - -```json -{ - "success": true, - "msg": "Got Alert By alertID", - "data": { - "_id": "66577ddae5ff3c91437d0887", - "checkId": "66577a3fd16dcf7c1ce35148", - "monitorId": "6657789ebf6766ee8e2d2edb", - "userId": "6654d1a2634754f789e1f115", - "status": false, - "message": "This is a test alert", - "notifiedStatus": false, - "acknowledgeStatus": false, - "createdAt": "2024-05-29T19:11:22.205Z", - "updatedAt": "2024-05-29T19:11:22.205Z", - "__v": 0 - } -} -``` - -
    - -
    -POST/api/v1/alerts/edit/{alertId} - -###### Method/Headers - -> | Method/Headers | Value | -> | -------------- | ----- | -> | Method | POST | - -###### Response Payload - -> | Type | Notes | -> | ------- | ---------------------- | -> | `Alert` | Returns edited `Alert` | - -###### Body - -> | Name | Type | Notes | -> | ----------------- | --------- | ------------------------------------------ | -> | checkId | `string` | ID of `Check` associated with `Alert` | -> | monitorId | `string` | ID of `Monitor` id associated with `Alert` | -> | userId | `string` | ID of `User` associated with `Alert` | -> | status | `boolean` | Alert status | -> | message | `string` | Alert message | -> | notifiedStatus | `boolean` | | -> | acknowledgeStatus | `boolean` | | - -##### Sample CURL request - -``` -curl --request POST \ - --url http://localhost:5000/api/v1/alerts/edit/66577ddae5ff3c91437d0887 \ - --header 'Authorization: ' \ - --header 'Content-Type: application/json' \ - --data '{ - "acknowledgeStatus": true -}' -``` - -###### Sample Response - -```json -{ - "success": true, - "msg": "Edited alert", - "data": { - "_id": "66577ddae5ff3c91437d0887", - "checkId": "66577a3fd16dcf7c1ce35148", - "monitorId": "6657789ebf6766ee8e2d2edb", - "userId": "6654d1a2634754f789e1f115", - "status": false, - "message": "This is a test alert", - "notifiedStatus": false, - "acknowledgeStatus": true, - "createdAt": "2024-05-29T19:11:22.205Z", - "updatedAt": "2024-05-29T19:12:23.951Z", - "__v": 0 - } -} -``` - -
    -
    -POST/api/v1/alerts/delete/{alertId} - -###### Method/Headers - -> | Method/Headers | Value | -> | -------------- | ----- | -> | Method | POST | - -###### Response Payload - -> | Type | Notes | -> | ------- | --------------------------- | -> | `Alert` | Returns the deleted `Alert` | - -##### Sample CURL request - -``` -curl --request POST \ - --url http://localhost:5000/api/v1/alerts/delete/66577ddae5ff3c91437d0887 \ - --header 'Authorization: ' \ -``` - -###### Sample Response - -```json -{ - "success": true, - "msg": "Deleted alert", - "data": { - "_id": "66577ddae5ff3c91437d0887", - "checkId": "66577a3fd16dcf7c1ce35148", - "monitorId": "6657789ebf6766ee8e2d2edb", - "userId": "6654d1a2634754f789e1f115", - "status": false, - "message": "This is a test alert", - "notifiedStatus": false, - "acknowledgeStatus": true, - "createdAt": "2024-05-29T19:11:22.205Z", - "updatedAt": "2024-05-29T19:12:23.951Z", - "__v": 0 - } -} -``` - -
    - ---- - -###### Checks - -
    -POST/api/v1/checks/{monitorId} - -###### Method/Headers - -> | Method/Headers | Value | -> | -------------- | ----- | -> | Method | POST | - -###### Response Payload - -> | Type | Notes | -> | ------- | --------------------------- | -> | `Check` | Returns newly created check | - -###### Body - -> | Name | Type | Notes | -> | ------------ | --------- | -------------------------------------- | -> | monitorId | `string` | Monitor associated with Check | -> | status | `boolean` | `true` for up and `false` for down | -> | responseTime | `number` | How long it took the server to respond | -> | statusCode | `number` | HTTP Status code of response | -> | message | `string` | | - -##### Sample CURL request - -``` -curl --request POST \ - --url http://localhost:5000/api/v1/checks/66562414035c4ce6a8a610ac \ - --header 'Authorization: ' \ - --header 'Content-Type: application/json' \ - --data '{ - "monitorId": "66562414035c4ce6a8a610ac", - "status": true, - "responseTime": 1, - "statusCode": 200, - "message": "good" -}' -``` - -###### Sample Response - -```json -{ - "success": true, - "msg": "Check created", - "data": { - "monitorId": "66562414035c4ce6a8a610ac", - "status": true, - "responseTime": 1, - "statusCode": 200, - "message": "good", - "_id": "66576decba9f70148ea1f354", - "createdAt": "2024-05-29T18:03:24.445Z", - "updatedAt": "2024-05-29T18:03:24.445Z", - "__v": 0 - } -} -``` - -
    - -
    -GET/api/v1/checks/{monitorId} - -###### Method/Headers - -> | Method/Headers | Value | -> | -------------- | ----- | -> | Method | GET | - -###### Response Payload - -> | Type | Notes | -> | --------------- | ------------------------ | -> | `Array` | Array of `Check` objects | - -##### Sample CURL request - -``` -curl --request GET \ - --url http://localhost:5000/api/v1/checks/66562414035c4ce6a8a610ac \ - --header 'Authorization: ' \ -``` - -###### Sample Response - -```json -{ - "success": true, - "msg": "Checks retrieved", - "data": [ - { - "_id": "66576c0194e11c0d4409d3c1", - "monitorId": "66562414035c4ce6a8a610ac", - "status": true, - "responseTime": 1, - "statusCode": 200, - "message": "good", - "createdAt": "2024-05-29T17:55:13.581Z", - "updatedAt": "2024-05-29T17:55:13.581Z", - "__v": 0 - }, - { - "_id": "66576c0994e11c0d4409d3c5", - "monitorId": "66562414035c4ce6a8a610ac", - "status": true, - "responseTime": 2, - "statusCode": 200, - "message": "good", - "createdAt": "2024-05-29T17:55:21.127Z", - "updatedAt": "2024-05-29T17:55:21.127Z", - "__v": 0 - } - ] -} -``` - -
    - -
    -POST/api/v1/checks/delete/{monitorId} - -###### Method/Headers - -> | Method/Headers | Value | -> | -------------- | ----- | -> | Method | POST | - -###### Response Payload - -> | Type | Notes | -> | -------- | -------------------------------------------------------------------- | -> | `Object` | `{deletedCount: n}` Returns an object showing how many items deleted | - -##### Sample CURL request - -``` -curl --request POST \ - --url http://localhost:5000/api/v1/checks/delete/66562414035c4ce6a8a610ac \ - --header 'Authorization: ' \ -``` - -###### Sample Response - -```json -{ - "success": true, - "msg": "Checks deleted", - "data": { - "deletedCount": 3 - } -} -``` - -
    - ---- - -###### Alerts - -
    -POST/api/v1/alerts/{monitorId} - -###### Method/Headers - -> | Method/Headers | Value | -> | -------------- | ----- | -> | Method | POST | - -###### Response Payload - -> | Type | Notes | -> | ------- | ----------------------------- | -> | `Alert` | Returns newly created `Alert` | - -###### Body - - "checkId": "66577a3fd16dcf7c1ce35148", - "monitorId": "6657789ebf6766ee8e2d2edb", - "userId": "6654d1a2634754f789e1f115", - "status": false, - "message": "This is a test alert", - "notifiedStatus": "false", - "acknowledgeStatus": false - -> | Name | Type | Notes | -> | ----------------- | --------- | --------------------------------------- | -> | checkId | `string` | Id of `Check` associated with `Alert` | -> | monitorId | `string` | Id of `Monitor` associated with `Alert` | -> | userId | `string` | Id of `User` associated with `Alert` | -> | status | `boolean` | Status of `Alert` | -> | message | `string` | `Alert` message | -> | notifiedStatus | `boolean` | | -> | acknowledgeStatus | `boolean` | | - -##### Sample CURL request - -``` - -``` - -###### Sample Response - -```json - -``` - -
    - -
    -GET/api/v1/alerts/user/{userId} - -###### Method/Headers - -> | Method/Headers | Value | -> | -------------- | ----- | -> | Method | GET | - -###### Response Payload - -> | Type | Notes | -> | -------------- | --------------------------------------- | -> | `Array` | Returns all `Alert` created by a `User` | - -##### Sample CURL request - -``` -curl --request GET \ - --url http://localhost:5000/api/v1/alerts/user/6654d1a2634754f789e1f115 \ - --header 'Authorization: ' -``` - -###### Sample Response - -```json -{ - "success": true, - "msg": "Got alerts", - "data": [ - { - "_id": "6657813d809adfded891a6b7", - "checkId": "66577a3fd16dcf7c1ce35148", - "monitorId": "6657789ebf6766ee8e2d2edb", - "userId": "6654d1a2634754f789e1f115", - "status": false, - "message": "This is a test alert", - "notifiedStatus": false, - "acknowledgeStatus": false, - "createdAt": "2024-05-29T19:25:49.317Z", - "updatedAt": "2024-05-29T19:25:49.317Z", - "__v": 0 - } - ] -} -``` - -
    -
    -GET/api/v1/alerts/monitor/{monitorId} - -###### Method/Headers - -> | Method/Headers | Value | -> | -------------- | ----- | -> | Method | GET | - -###### Response Payload - -> | Type | Notes | -> | -------------- | -------------------------------------------------------------- | -> | `Array` | Returns an array of `Alert` belonging to a specified `Monitor` | - -##### Sample CURL request - -``` -curl --request GET \ - --url http://localhost:5000/api/v1/alerts/monitor/6657789ebf6766ee8e2d2edb \ - --header 'Authorization: ' \ -``` - -###### Sample Response - -```json -{ - "success": true, - "msg": "Got alerts by Monitor", - "data": [ - { - "_id": "6657813d809adfded891a6b7", - "checkId": "66577a3fd16dcf7c1ce35148", - "monitorId": "6657789ebf6766ee8e2d2edb", - "userId": "6654d1a2634754f789e1f115", - "status": false, - "message": "This is a test alert", - "notifiedStatus": false, - "acknowledgeStatus": false, - "createdAt": "2024-05-29T19:25:49.317Z", - "updatedAt": "2024-05-29T19:25:49.317Z", - "__v": 0 - } - ] -} -``` - -
    - -
    -GET/api/v1/alerts/{alertId} - -###### Method/Headers - -> | Method/Headers | Value | -> | -------------- | ----- | -> | Method | GET | - -###### Response Payload - -> | Type | Notes | -> | ------- | ------------------------- | -> | `Alert` | Returns specified `Alert` | - -##### Sample CURL request - -``` -curl --request GET \ - --url http://localhost:5000/api/v1/alerts/66577ddae5ff3c91437d0887 \ - --header 'Authorization: ' \ -``` - -###### Sample Response - -```json -{ - "success": true, - "msg": "Got Alert By alertID", - "data": { - "_id": "66577ddae5ff3c91437d0887", - "checkId": "66577a3fd16dcf7c1ce35148", - "monitorId": "6657789ebf6766ee8e2d2edb", - "userId": "6654d1a2634754f789e1f115", - "status": false, - "message": "This is a test alert", - "notifiedStatus": false, - "acknowledgeStatus": false, - "createdAt": "2024-05-29T19:11:22.205Z", - "updatedAt": "2024-05-29T19:11:22.205Z", - "__v": 0 - } -} -``` - -
    - -
    -POST/api/v1/alerts/edit/{alertId} - -###### Method/Headers - -> | Method/Headers | Value | -> | -------------- | ----- | -> | Method | POST | - -###### Response Payload - -> | Type | Notes | -> | ------- | ---------------------- | -> | `Alert` | Returns edited `Alert` | - -###### Body - -> | Name | Type | Notes | -> | ----------------- | --------- | ------------------------------------------ | -> | checkId | `string` | ID of `Check` associated with `Alert` | -> | monitorId | `string` | ID of `Monitor` id associated with `Alert` | -> | userId | `string` | ID of `User` associated with `Alert` | -> | status | `boolean` | Alert status | -> | message | `string` | Alert message | -> | notifiedStatus | `boolean` | | -> | acknowledgeStatus | `boolean` | | - -##### Sample CURL request - -``` -curl --request POST \ - --url http://localhost:5000/api/v1/alerts/edit/66577ddae5ff3c91437d0887 \ - --header 'Authorization: ' \ - --header 'Content-Type: application/json' \ - --data '{ - "acknowledgeStatus": true -}' -``` - -###### Sample Response - -```json -{ - "success": true, - "msg": "Edited alert", - "data": { - "_id": "66577ddae5ff3c91437d0887", - "checkId": "66577a3fd16dcf7c1ce35148", - "monitorId": "6657789ebf6766ee8e2d2edb", - "userId": "6654d1a2634754f789e1f115", - "status": false, - "message": "This is a test alert", - "notifiedStatus": false, - "acknowledgeStatus": true, - "createdAt": "2024-05-29T19:11:22.205Z", - "updatedAt": "2024-05-29T19:12:23.951Z", - "__v": 0 - } -} -``` - -
    -
    -POST/api/v1/alerts/delete/{alertId} - -###### Method/Headers - -> | Method/Headers | Value | -> | -------------- | ----- | -> | Method | POST | - -###### Response Payload - -> | Type | Notes | -> | ------- | --------------------------- | -> | `Alert` | Returns the deleted `Alert` | - -##### Sample CURL request - -``` -curl --request POST \ - --url http://localhost:5000/api/v1/alerts/delete/66577ddae5ff3c91437d0887 \ - --header 'Authorization: ' \ -``` - -###### Sample Response - -```json -{ - "success": true, - "msg": "Deleted alert", - "data": { - "_id": "66577ddae5ff3c91437d0887", - "checkId": "66577a3fd16dcf7c1ce35148", - "monitorId": "6657789ebf6766ee8e2d2edb", - "userId": "6654d1a2634754f789e1f115", - "status": false, - "message": "This is a test alert", - "notifiedStatus": false, - "acknowledgeStatus": true, - "createdAt": "2024-05-29T19:11:22.205Z", - "updatedAt": "2024-05-29T19:12:23.951Z", - "__v": 0 - } -} -``` - -
    - ---- +You can also view the documentation on our demo server at [https://uptime-demo.bluewavelabs.ca/api-docs](https://uptime-demo.bluewavelabs.ca/api-docs) ### Error handling From 5dbd8378e28d3dedaeba6dd3e49d9b200e9855bf Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Wed, 25 Sep 2024 15:12:07 +0800 Subject: [PATCH 54/98] require invite token to register except for initial registration --- Client/src/Pages/Auth/Register/Register.jsx | 5 ++-- Client/src/Validation/validation.js | 1 + Server/controllers/authController.js | 5 ++++ Server/db/mongo/MongoDB.js | 2 ++ Server/db/mongo/modules/inviteModule.js | 30 ++++++++++++++++++++- Server/validation/joi.js | 2 ++ 6 files changed, 42 insertions(+), 3 deletions(-) diff --git a/Client/src/Pages/Auth/Register/Register.jsx b/Client/src/Pages/Auth/Register/Register.jsx index 7f5ed6390..eb331304c 100644 --- a/Client/src/Pages/Auth/Register/Register.jsx +++ b/Client/src/Pages/Auth/Register/Register.jsx @@ -596,6 +596,7 @@ const Register = ({ isSuperAdmin }) => { let registerForm = { ...form, role: isSuperAdmin ? ["superadmin"] : form.role, + inviteToken: token ? token : "", }; let error = validateForm(registerForm, { context: { password: form.password }, @@ -608,8 +609,8 @@ const Register = ({ isSuperAdmin }) => { delete registerForm.confirm; const action = await dispatch(register(registerForm)); if (action.payload.success) { - const token = action.payload.data; - localStorage.setItem("token", token); + const authToken = action.payload.data; + localStorage.setItem("token", authToken); navigate("/"); createToast({ body: "Welcome! Your account was created successfully.", diff --git a/Client/src/Validation/validation.js b/Client/src/Validation/validation.js index 3d11482d1..25ad79923 100644 --- a/Client/src/Validation/validation.js +++ b/Client/src/Validation/validation.js @@ -77,6 +77,7 @@ const credentials = joi.object({ }), role: joi.array(), teamId: joi.string().allow("").optional(), + inviteToken: joi.string().allow(""), }); const monitorValidation = joi.object({ diff --git a/Server/controllers/authController.js b/Server/controllers/authController.js index f39ffb019..6357d25de 100644 --- a/Server/controllers/authController.js +++ b/Server/controllers/authController.js @@ -51,6 +51,11 @@ const registerController = async (req, res, next) => { } // Create a new user try { + const { inviteToken } = req.body; + const superAdminExists = await req.db.checkSuperadmin(req, res); + if (superAdminExists) { + await req.db.getInviteTokenAndDelete(inviteToken); + } const newUser = await req.db.insertUser({ ...req.body }, req.file); logger.info(successMessages.AUTH_CREATE_USER, { service: SERVICE_NAME, diff --git a/Server/db/mongo/MongoDB.js b/Server/db/mongo/MongoDB.js index c5fcff08c..0cc2d5b57 100644 --- a/Server/db/mongo/MongoDB.js +++ b/Server/db/mongo/MongoDB.js @@ -47,6 +47,7 @@ const { const { requestInviteToken, getInviteToken, + getInviteTokenAndDelete, } = require("./modules/inviteModule"); //**************************************** @@ -128,6 +129,7 @@ module.exports = { logoutUser, requestInviteToken, getInviteToken, + getInviteTokenAndDelete, requestRecoveryToken, validateRecoveryToken, resetPassword, diff --git a/Server/db/mongo/modules/inviteModule.js b/Server/db/mongo/modules/inviteModule.js index 6e810ec8b..1b7d698cd 100644 --- a/Server/db/mongo/modules/inviteModule.js +++ b/Server/db/mongo/modules/inviteModule.js @@ -32,7 +32,7 @@ const requestInviteToken = async (userData) => { }; /** - * Retrieves and deletes an invite token. + * Retrieves an invite token * * This function searches for an invite token in the database and deletes it. * If the invite token is not found, it throws an error. @@ -42,6 +42,33 @@ const requestInviteToken = async (userData) => { * @throws {Error} If the invite token is not found or there is another error. */ const getInviteToken = async (token) => { + console.log(token); + try { + const invite = await InviteToken.findOne({ + token, + }); + if (invite === null) { + throw new Error(errorMessages.AUTH_INVITE_NOT_FOUND); + } + return invite; + } catch (error) { + error.service = SERVICE_NAME; + error.method = "getInviteToken"; + throw error; + } +}; + +/** + * Retrieves and deletes an invite token + * + * This function searches for an invite token in the database and deletes it. + * If the invite token is not found, it throws an error. + * + * @param {string} token - The invite token to search for. + * @returns {Promise} The invite token data. + * @throws {Error} If the invite token is not found or there is another error. + */ +const getInviteTokenAndDelete = async (token) => { try { const invite = await InviteToken.findOneAndDelete({ token, @@ -60,4 +87,5 @@ const getInviteToken = async (token) => { module.exports = { requestInviteToken, getInviteToken, + getInviteTokenAndDelete, }; diff --git a/Server/validation/joi.js b/Server/validation/joi.js index f61432595..0a83b6e74 100644 --- a/Server/validation/joi.js +++ b/Server/validation/joi.js @@ -74,6 +74,7 @@ const registrationBodyValidation = joi.object({ .min(1) .required(), teamId: joi.string().allow("").required(), + inviteToken: joi.string().allow("").required(), }); const editUserParamValidation = joi.object({ @@ -137,6 +138,7 @@ const inviteBodyValidation = joi.object({ "string.email": "Must be a valid email address", }), role: joi.array().required(), + teamId: joi.string().required(), }); const inviteVerifciationBodyValidation = joi.object({ From ffd193437e1285f7b04318dace01e342b208dca7 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Wed, 25 Sep 2024 15:14:22 +0800 Subject: [PATCH 55/98] add comments --- Client/src/Pages/Auth/Register/Register.jsx | 2 +- Server/controllers/authController.js | 1 + Server/db/mongo/modules/inviteModule.js | 1 - 3 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Client/src/Pages/Auth/Register/Register.jsx b/Client/src/Pages/Auth/Register/Register.jsx index eb331304c..c9f61adae 100644 --- a/Client/src/Pages/Auth/Register/Register.jsx +++ b/Client/src/Pages/Auth/Register/Register.jsx @@ -596,7 +596,7 @@ const Register = ({ isSuperAdmin }) => { let registerForm = { ...form, role: isSuperAdmin ? ["superadmin"] : form.role, - inviteToken: token ? token : "", + inviteToken: token ? token : "", // Add the token to the request for verification }; let error = validateForm(registerForm, { context: { password: form.password }, diff --git a/Server/controllers/authController.js b/Server/controllers/authController.js index 6357d25de..4e589ac8a 100644 --- a/Server/controllers/authController.js +++ b/Server/controllers/authController.js @@ -52,6 +52,7 @@ const registerController = async (req, res, next) => { // Create a new user try { const { inviteToken } = req.body; + // If superAdmin exists, a token should be attached to all further register requests const superAdminExists = await req.db.checkSuperadmin(req, res); if (superAdminExists) { await req.db.getInviteTokenAndDelete(inviteToken); diff --git a/Server/db/mongo/modules/inviteModule.js b/Server/db/mongo/modules/inviteModule.js index 1b7d698cd..9a0d35621 100644 --- a/Server/db/mongo/modules/inviteModule.js +++ b/Server/db/mongo/modules/inviteModule.js @@ -42,7 +42,6 @@ const requestInviteToken = async (userData) => { * @throws {Error} If the invite token is not found or there is another error. */ const getInviteToken = async (token) => { - console.log(token); try { const invite = await InviteToken.findOne({ token, From 888f644c7cef07f64269f4b8736027fa6238b2b0 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Thu, 26 Sep 2024 10:28:48 +0800 Subject: [PATCH 56/98] user -> User --- Server/db/FakeDb.js | 2 +- Server/db/mongo/MongoDB.js | 2 +- Server/db/mongo/modules/checkModule.js | 2 +- Server/db/mongo/modules/recoveryModule.js | 2 +- Server/db/mongo/modules/userModule.js | 2 +- Server/middleware/verifyJWT.js | 2 +- Server/models/{user.js => User.js} | 0 Server/routes/authRoute.js | 2 +- 8 files changed, 7 insertions(+), 7 deletions(-) rename Server/models/{user.js => User.js} (100%) diff --git a/Server/db/FakeDb.js b/Server/db/FakeDb.js index 6a65bf502..e4f36d001 100644 --- a/Server/db/FakeDb.js +++ b/Server/db/FakeDb.js @@ -21,7 +21,7 @@ // ************************** const Monitor = require("../models/Monitor"); -const UserModel = require("../models/user"); +const UserModel = require("../models/User"); const bcrypt = require("bcrypt"); let FAKE_MONITOR_DATA = []; diff --git a/Server/db/mongo/MongoDB.js b/Server/db/mongo/MongoDB.js index 0cc2d5b57..35120c966 100644 --- a/Server/db/mongo/MongoDB.js +++ b/Server/db/mongo/MongoDB.js @@ -1,5 +1,5 @@ const mongoose = require("mongoose"); -const UserModel = require("../../models/user"); +const UserModel = require("../../models/User"); //**************************************** // DB Connection diff --git a/Server/db/mongo/modules/checkModule.js b/Server/db/mongo/modules/checkModule.js index 6ab1fd51b..c18491021 100644 --- a/Server/db/mongo/modules/checkModule.js +++ b/Server/db/mongo/modules/checkModule.js @@ -1,6 +1,6 @@ const Check = require("../../../models/Check"); const Monitor = require("../../../models/Monitor"); -const User = require("../../../models/user"); +const User = require("../../../models/User"); const logger = require("../../../utils/logger"); const SERVICE_NAME = "checkModule"; const dateRangeLookup = { diff --git a/Server/db/mongo/modules/recoveryModule.js b/Server/db/mongo/modules/recoveryModule.js index 3f5c14819..469954cef 100644 --- a/Server/db/mongo/modules/recoveryModule.js +++ b/Server/db/mongo/modules/recoveryModule.js @@ -1,4 +1,4 @@ -const UserModel = require("../../../models/user"); +const UserModel = require("../../../models/User"); const RecoveryToken = require("../../../models/RecoveryToken"); const crypto = require("crypto"); const { errorMessages } = require("../../../utils/messages"); diff --git a/Server/db/mongo/modules/userModule.js b/Server/db/mongo/modules/userModule.js index 37446623e..e602e84b5 100644 --- a/Server/db/mongo/modules/userModule.js +++ b/Server/db/mongo/modules/userModule.js @@ -1,4 +1,4 @@ -const UserModel = require("../../../models/user"); +const UserModel = require("../../../models/User"); const TeamModel = require("../../../models/Team"); const { errorMessages } = require("../../../utils/messages"); const { GenerateAvatarImage } = require("../../../utils/imageProcessing"); diff --git a/Server/middleware/verifyJWT.js b/Server/middleware/verifyJWT.js index d79c2eddc..9d50fe7ea 100644 --- a/Server/middleware/verifyJWT.js +++ b/Server/middleware/verifyJWT.js @@ -4,7 +4,7 @@ const SERVICE_NAME = "verifyJWT"; const TOKEN_PREFIX = "Bearer "; const { errorMessages } = require("../utils/messages"); const { parse } = require("path"); -const User = require("../models/user"); +const User = require("../models/User"); /** * Verifies the JWT token * @function diff --git a/Server/models/user.js b/Server/models/User.js similarity index 100% rename from Server/models/user.js rename to Server/models/User.js diff --git a/Server/routes/authRoute.js b/Server/routes/authRoute.js index 743a55c19..362f6a5a2 100644 --- a/Server/routes/authRoute.js +++ b/Server/routes/authRoute.js @@ -4,7 +4,7 @@ const { verifyOwnership } = require("../middleware/verifyOwnership"); const { isAllowed } = require("../middleware/isAllowed"); const multer = require("multer"); const upload = multer(); -const User = require("../models/user"); +const User = require("../models/User"); const { registerController, From 09fb5595abe0b19f68aff7031874e1a667e8f68d Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Thu, 26 Sep 2024 10:42:03 +0800 Subject: [PATCH 57/98] Fix proptype errors, remove old alert reference --- Client/src/Pages/Monitors/Home/index.jsx | 2 +- Client/src/Pages/PageSpeed/Details/index.jsx | 2 +- Server/controllers/monitorController.js | 26 +++++++++++--------- 3 files changed, 17 insertions(+), 13 deletions(-) diff --git a/Client/src/Pages/Monitors/Home/index.jsx b/Client/src/Pages/Monitors/Home/index.jsx index c2a532bb9..a03959076 100644 --- a/Client/src/Pages/Monitors/Home/index.jsx +++ b/Client/src/Pages/Monitors/Home/index.jsx @@ -134,7 +134,7 @@ const Monitors = ({ isAdmin }) => { { normalize: null, }); setMonitor(res?.data?.data ?? {}); - setAudits(res?.data?.data?.checks?.[0]?.audits ?? []); + setAudits(res?.data?.data?.checks?.[0]?.audits ?? {}); } catch (error) { logger.error(logger); navigate("/not-found", { replace: true }); diff --git a/Server/controllers/monitorController.js b/Server/controllers/monitorController.js index e534e0f60..a8b90c084 100644 --- a/Server/controllers/monitorController.js +++ b/Server/controllers/monitorController.js @@ -20,6 +20,7 @@ const SERVICE_NAME = "monitorController"; const { errorMessages, successMessages } = require("../utils/messages"); const jwt = require("jsonwebtoken"); const { getTokenFromHeaders } = require("../utils/utils"); +const logger = require("../utils/logger"); /** * Returns all monitors @@ -315,18 +316,21 @@ const deleteMonitor = async (req, res, next) => { try { const monitor = await req.db.deleteMonitor(req, res, next); // Delete associated checks,alerts,and notifications - await req.jobQueue.deleteJob(monitor); - await req.db.deleteChecks(monitor._id); - await req.db.deleteAlertByMonitorId(monitor._id); - await req.db.deletePageSpeedChecksByMonitorId(monitor._id); - await req.db.deleteNotificationsByMonitorId(monitor._id); + try { + await req.jobQueue.deleteJob(monitor); + await req.db.deleteChecks(monitor._id); + await req.db.deletePageSpeedChecksByMonitorId(monitor._id); + await req.db.deleteNotificationsByMonitorId(monitor._id); + } catch (error) { + logger.error( + `Error deleting associated records for monitor ${monitor._id} with name ${monitor.name}`, + { + service: SERVICE_NAME, + error: error.message, + } + ); + } - /** - * TODO - * We should remove all checks and alerts associated with this monitor - * when it is deleted so there is no orphaned data - * We also need to make sure to stop all running services for this monitor - */ return res .status(200) .json({ success: true, msg: successMessages.MONITOR_DELETE }); From 38ee162f619d7217452d95b1d2594210b2967836 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Thu, 26 Sep 2024 11:01:38 +0800 Subject: [PATCH 58/98] improve error handling in network service, fix username form errors --- Client/src/Components/Inputs/Field/index.jsx | 11 ++++++++++- .../Components/TabPanels/Account/PasswordPanel.jsx | 10 +++++++++- Server/controllers/monitorController.js | 1 + Server/service/networkService.js | 11 +++++++++-- 4 files changed, 29 insertions(+), 4 deletions(-) diff --git a/Client/src/Components/Inputs/Field/index.jsx b/Client/src/Components/Inputs/Field/index.jsx index e7326ec41..1843a411b 100644 --- a/Client/src/Components/Inputs/Field/index.jsx +++ b/Client/src/Components/Inputs/Field/index.jsx @@ -16,6 +16,7 @@ import "./index.css"; * @param {Object} props * @param {string} [props.type] - Type of input field (e.g., 'text', 'password'). * @param {string} props.id - ID of the input field. + * @param {string} props.name - Name of the input field. * @param {string} [props.label] - Label for the input field. * @param {boolean} [props.https] - Indicates if it should display http or https. * @param {boolean} [props.isRequired] - Indicates if the field is required, will display a red asterisk. @@ -27,6 +28,7 @@ import "./index.css"; * @param {function} props.onChange - Function called on input change. * @param {string} [props.error] - Error message to display for the input field. * @param {boolean} [props.disabled] - Indicates if the input field is disabled. + * @param {boolean} [props.hidden] - Indicates if the input field is hidden. * @param {React.Ref} [ref] - Ref forwarded to the underlying `TextField` component. Allows for direct interactions such as focusing. */ @@ -35,6 +37,7 @@ const Field = forwardRef( { type = "text", id, + name, label, https, isRequired, @@ -47,6 +50,7 @@ const Field = forwardRef( onInput, error, disabled, + hidden, }, ref ) => { @@ -107,6 +111,7 @@ const Field = forwardRef( )} ); diff --git a/Client/src/Utils/Logger.js b/Client/src/Utils/Logger.js index 02fffd6be..79b2ed4f9 100644 --- a/Client/src/Utils/Logger.js +++ b/Client/src/Utils/Logger.js @@ -1,6 +1,16 @@ -const LOG_LEVEL = import.meta.env.VITE_APP_LOG_LEVEL; +import store from "../store"; +const LOG_LEVEL = import.meta.env.VITE_APP_LOG_LEVEL || "debug"; class Logger { - constructor(logLevel) { + constructor() { + let logLevel = LOG_LEVEL; + this.unsubscribe = store.subscribe(() => { + const state = store.getState(); + logLevel = state.settings.logLevel || "debug"; + this.updateLogLevel(logLevel); + }); + } + + updateLogLevel(logLevel) { const NO_OP = () => {}; if (logLevel === "none") { @@ -25,6 +35,12 @@ class Logger { } this.log = console.log.bind(console); } + + cleanup() { + if (this.unsubscribe) { + this.unsubscribe(); + } + } } -export const logger = new Logger(LOG_LEVEL); +export const logger = new Logger(); diff --git a/Client/src/Utils/NetworkService.js b/Client/src/Utils/NetworkService.js index 9545fb247..00b52f7f7 100644 --- a/Client/src/Utils/NetworkService.js +++ b/Client/src/Utils/NetworkService.js @@ -1,10 +1,18 @@ import axios from "axios"; -const BASE_URL = import.meta.env.VITE_APP_API_BASE_URL; +const BASE_URL = + import.meta.env.VITE_APP_API_BASE_URL || "http://localhost:5000/api/v1"; import { logger } from "./Logger"; class NetworkService { constructor(store) { this.store = store; - this.axiosInstance = axios.create({ baseURL: BASE_URL }); + let baseURL = BASE_URL; + this.axiosInstance = axios.create(); + this.setBaseUrl(baseURL); + this.unsubscribe = store.subscribe(() => { + const state = store.getState(); + baseURL = state.settings.apiBaseUrl || BASE_URL; + this.setBaseUrl(baseURL); + }); this.axiosInstance.interceptors.response.use( (response) => response, (error) => { @@ -17,6 +25,16 @@ class NetworkService { ); } + setBaseUrl = (url) => { + this.axiosInstance.defaults.baseURL = url; + }; + + cleanup() { + if (this.unsubscribe) { + this.unsubscribe(); + } + } + /** * * ************************************ @@ -640,6 +658,27 @@ class NetworkService { }, }); } + + /** + * + * ************************************ + * Create a new monitor + * ************************************ + * + * @async + * @param {Object} config - The configuration object. + * @param {string} config.authToken - The authorization token to be used in the request header. + * @param {Object} config.settings - The monitor object to be sent in the request body. + * @returns {Promise} The response from the axios POST request. + */ + async updateAppSettings(config) { + return this.axiosInstance.put(`/settings`, config.settings, { + headers: { + Authorization: `Bearer ${config.authToken}`, + "Content-Type": "application/json", + }, + }); + } } export default NetworkService; diff --git a/Client/src/store.js b/Client/src/store.js index 10c296392..644da5e62 100644 --- a/Client/src/store.js +++ b/Client/src/store.js @@ -51,3 +51,4 @@ export const store = configureStore({ }); export const persistor = persistStore(store); +export default store; From d418e2f1f860b1a0428bc5b5e6188ba683595762 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Fri, 27 Sep 2024 12:22:50 +0800 Subject: [PATCH 69/98] Add remainder of settings --- Client/src/Pages/AdvancedSettings/index.jsx | 78 ++++++++++++++++++--- 1 file changed, 68 insertions(+), 10 deletions(-) diff --git a/Client/src/Pages/AdvancedSettings/index.jsx b/Client/src/Pages/AdvancedSettings/index.jsx index 61cdd86a9..59e677138 100644 --- a/Client/src/Pages/AdvancedSettings/index.jsx +++ b/Client/src/Pages/AdvancedSettings/index.jsx @@ -1,8 +1,7 @@ import { useTheme } from "@emotion/react"; -import { Box, Stack, Typography, Button } from "@mui/material"; +import { Box, Stack, Typography } from "@mui/material"; import Field from "../../Components/Inputs/Field"; import Link from "../../Components/Link"; -import { logger } from "../../Utils/Logger"; import "./index.css"; import { useDispatch, useSelector } from "react-redux"; import { createToast } from "../../Utils/toastUtils"; @@ -10,18 +9,19 @@ import PropTypes from "prop-types"; import LoadingButton from "@mui/lab/LoadingButton"; import { ConfigBox } from "../Settings/styled"; import { useNavigate } from "react-router"; -import { - getAppSettings, - updateAppSettings, -} from "../../Features/Settings/settingsSlice"; -import { useEffect, useState } from "react"; +import { updateAppSettings } from "../../Features/Settings/settingsSlice"; +import { useState } from "react"; import Select from "../../Components/Inputs/Select"; const AdvancedSettings = ({ isAdmin }) => { - const theme = useTheme(); - const { user, authToken } = useSelector((state) => state.auth); - const dispatch = useDispatch(); const navigate = useNavigate(); + if (!isAdmin) { + navigate("/"); + } + + const theme = useTheme(); + const { authToken } = useSelector((state) => state.auth); + const dispatch = useDispatch(); const settings = useSelector((state) => state.settings); const [localSettings, setLocalSettings] = useState(settings); const logItems = [ @@ -143,6 +143,64 @@ const AdvancedSettings = ({ isAdmin }) => { /> + + + Server Settings + + Modify server settings here + + + + + + + + + + + About From c3edbb779a690f09ab16c647a5998090cf12f8bd Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Fri, 27 Sep 2024 13:02:01 +0800 Subject: [PATCH 70/98] Modify settingsService to load from env by default --- Server/service/settingsService.js | 52 ++++++++++++++++++++++++------- 1 file changed, 40 insertions(+), 12 deletions(-) diff --git a/Server/service/settingsService.js b/Server/service/settingsService.js index a5e7b2734..ca2509fe0 100644 --- a/Server/service/settingsService.js +++ b/Server/service/settingsService.js @@ -1,24 +1,52 @@ const AppSettings = require("../models/AppSettings"); const SERVICE_NAME = "SettingsService"; +CLIENT_HOST = process.env.CLIENT_HOST; +JWT_SECRET = process.env.JWT_SECRET; +DB_TYPE = process.env.DB_TYPE; +DB_CONNECTION_STRING = process.env.DB_CONNECTION_STRING; +REDIS_HOST = process.env.REDIS_HOST; +REDIS_PORT = process.env.REDIS_PORT; +TOKEN_TTL = process.env.TOKEN_TTL; +PAGESPEED_API_KEY = process.env.PAGESPEED_API_KEY; +SYSTEM_EMAIL_HOST = process.env.SYSTEM_EMAIL_HOST; +SYSTEM_EMAIL_PORT = process.env.SYSTEM_EMAIL_PORT; +SYSTEM_EMAIL_ADDRESS = process.env.SYSTEM_EMAIL_ADDRESS; +SYSTEM_EMAIL_PASSWORD = process.env.SYSTEM_EMAIL_PASSWORD; class SettingsService { constructor() { - this.settings = null; + this.settings = { + clientHost: CLIENT_HOST, + jwtSecret: JWT_SECRET, + dbType: DB_TYPE, + dbConnectionString: DB_CONNECTION_STRING, + redisHost: REDIS_HOST, + redisPort: REDIS_PORT, + tokenTTL: TOKEN_TTL, + pagespeedApiKey: PAGESPEED_API_KEY, + systemEmailHost: SYSTEM_EMAIL_HOST, + systemEmailPort: SYSTEM_EMAIL_PORT, + systemEmailAddress: SYSTEM_EMAIL_ADDRESS, + systemEmailPassword: SYSTEM_EMAIL_PASSWORD, + }; } async loadSettings() { - if (!this.settings) { - try { - this.settings = await AppSettings.findOne(); - if (!this.settings) { - throw new Error("Settings not found"); - } - return this.settings; - } catch (error) { - error.service === undefined ? (error.service = SERVICE_NAME) : null; - error.method === undefined ? (error.method = "loadSettings") : null; - throw error; + try { + const dbSettings = await AppSettings.findOne(); + if (!this.settings) { + throw new Error("Settings not found"); } + for (const key in this.settings) { + if (this.settings[key] === undefined && dbSettings[key] !== undefined) { + this.settings[key] = dbSettings[key]; + } + } + return this.settings; + } catch (error) { + error.service === undefined ? (error.service = SERVICE_NAME) : null; + error.method === undefined ? (error.method = "loadSettings") : null; + throw error; } } From f4bbbc5fa9f299e7b6db172d1f67ee0609a7b25d Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Fri, 27 Sep 2024 13:10:29 +0800 Subject: [PATCH 71/98] fix conditional loadingof settings --- Server/service/settingsService.js | 55 ++++++++++++++----------------- 1 file changed, 25 insertions(+), 30 deletions(-) diff --git a/Server/service/settingsService.js b/Server/service/settingsService.js index ca2509fe0..b1027a17c 100644 --- a/Server/service/settingsService.js +++ b/Server/service/settingsService.js @@ -1,34 +1,23 @@ +const { env } = require("process"); const AppSettings = require("../models/AppSettings"); const SERVICE_NAME = "SettingsService"; - -CLIENT_HOST = process.env.CLIENT_HOST; -JWT_SECRET = process.env.JWT_SECRET; -DB_TYPE = process.env.DB_TYPE; -DB_CONNECTION_STRING = process.env.DB_CONNECTION_STRING; -REDIS_HOST = process.env.REDIS_HOST; -REDIS_PORT = process.env.REDIS_PORT; -TOKEN_TTL = process.env.TOKEN_TTL; -PAGESPEED_API_KEY = process.env.PAGESPEED_API_KEY; -SYSTEM_EMAIL_HOST = process.env.SYSTEM_EMAIL_HOST; -SYSTEM_EMAIL_PORT = process.env.SYSTEM_EMAIL_PORT; -SYSTEM_EMAIL_ADDRESS = process.env.SYSTEM_EMAIL_ADDRESS; -SYSTEM_EMAIL_PASSWORD = process.env.SYSTEM_EMAIL_PASSWORD; +const envConfig = { + clientHost: process.env.CLIENT_HOST, + jwtSecret: process.env.JWT_SECRET, + dbType: process.env.DB_TYPE, + dbConnectionString: process.env.DB_CONNECTION_STRING, + redisHost: process.env.REDIS_HOST, + redisPort: process.env.REDIS_PORT, + tokenTTL: process.env.TOKEN_TTL, + pagespeedApiKey: process.env.PAGESPEED_API_KEY, + systemEmailHost: process.env.SYSTEM_EMAIL_HOST, + systemEmailPort: process.env.SYSTEM_EMAIL_PORT, + systemEmailAddress: process.env.SYSTEM_EMAIL_ADDRESS, + systemEmailPassword: process.env.SYSTEM_EMAIL_PASSWORD, +}; class SettingsService { constructor() { - this.settings = { - clientHost: CLIENT_HOST, - jwtSecret: JWT_SECRET, - dbType: DB_TYPE, - dbConnectionString: DB_CONNECTION_STRING, - redisHost: REDIS_HOST, - redisPort: REDIS_PORT, - tokenTTL: TOKEN_TTL, - pagespeedApiKey: PAGESPEED_API_KEY, - systemEmailHost: SYSTEM_EMAIL_HOST, - systemEmailPort: SYSTEM_EMAIL_PORT, - systemEmailAddress: SYSTEM_EMAIL_ADDRESS, - systemEmailPassword: SYSTEM_EMAIL_PASSWORD, - }; + this.settings = envConfig; } async loadSettings() { @@ -37,8 +26,8 @@ class SettingsService { if (!this.settings) { throw new Error("Settings not found"); } - for (const key in this.settings) { - if (this.settings[key] === undefined && dbSettings[key] !== undefined) { + for (const key in envConfig) { + if (envConfig[key] === undefined && dbSettings[key] !== undefined) { this.settings[key] = dbSettings[key]; } } @@ -52,7 +41,13 @@ class SettingsService { async reloadSettings() { try { - this.settings = await AppSettings.findOne(); + const dbSettings = await AppSettings.findOne(); + + for (const key in envConfig) { + if (envConfig[key] === undefined && dbSettings[key] !== undefined) { + this.settings[key] = dbSettings[key]; + } + } if (!this.settings) { throw new Error("Settings not found"); } From 43a56e1de14e95e5e0a227d4a954b1636aea0a50 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Fri, 27 Sep 2024 13:17:28 +0800 Subject: [PATCH 72/98] Fix setting name --- Server/service/settingsService.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Server/service/settingsService.js b/Server/service/settingsService.js index b1027a17c..abec31146 100644 --- a/Server/service/settingsService.js +++ b/Server/service/settingsService.js @@ -8,7 +8,7 @@ const envConfig = { dbConnectionString: process.env.DB_CONNECTION_STRING, redisHost: process.env.REDIS_HOST, redisPort: process.env.REDIS_PORT, - tokenTTL: process.env.TOKEN_TTL, + jwtTTL: process.env.TOKEN_TTL, pagespeedApiKey: process.env.PAGESPEED_API_KEY, systemEmailHost: process.env.SYSTEM_EMAIL_HOST, systemEmailPort: process.env.SYSTEM_EMAIL_PORT, From b8984c01603aeae8171a2416cf2abd2bd87087ea Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Fri, 27 Sep 2024 13:38:57 +0800 Subject: [PATCH 73/98] Restrict access to advanced settings page --- Client/src/Pages/AdvancedSettings/index.jsx | 12 ++++--- Client/src/Pages/Settings/index.jsx | 38 +++++++++++---------- 2 files changed, 27 insertions(+), 23 deletions(-) diff --git a/Client/src/Pages/AdvancedSettings/index.jsx b/Client/src/Pages/AdvancedSettings/index.jsx index 59e677138..29a9fe53c 100644 --- a/Client/src/Pages/AdvancedSettings/index.jsx +++ b/Client/src/Pages/AdvancedSettings/index.jsx @@ -10,14 +10,17 @@ import LoadingButton from "@mui/lab/LoadingButton"; import { ConfigBox } from "../Settings/styled"; import { useNavigate } from "react-router"; import { updateAppSettings } from "../../Features/Settings/settingsSlice"; -import { useState } from "react"; +import { useState, useEffect } from "react"; import Select from "../../Components/Inputs/Select"; const AdvancedSettings = ({ isAdmin }) => { const navigate = useNavigate(); - if (!isAdmin) { - navigate("/"); - } + + useEffect(() => { + if (!isAdmin) { + navigate("/"); + } + }, [navigate, isAdmin]); const theme = useTheme(); const { authToken } = useSelector((state) => state.auth); @@ -75,7 +78,6 @@ const AdvancedSettings = ({ isAdmin }) => { noValidate spellCheck="false" > - \{" "} Client Settings diff --git a/Client/src/Pages/Settings/index.jsx b/Client/src/Pages/Settings/index.jsx index 63199f9f4..bf8cfcc79 100644 --- a/Client/src/Pages/Settings/index.jsx +++ b/Client/src/Pages/Settings/index.jsx @@ -251,26 +251,28 @@ const Settings = ({ isAdmin }) => { )} - - - Advanced Settings - - Click here to modify advanced settings - - - + {isAdmin && ( + - + Advanced Settings + + Click here to modify advanced settings + - - + + + + + + + )} About From 453c8f6b12e474eac14b1118af27f2502486ad02 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Fri, 27 Sep 2024 13:46:50 +0800 Subject: [PATCH 74/98] bump FE dependencies --- Client/package-lock.json | 170 ++++++++++++++++++++------------------- 1 file changed, 87 insertions(+), 83 deletions(-) diff --git a/Client/package-lock.json b/Client/package-lock.json index 2f1543bba..4077ce2bf 100644 --- a/Client/package-lock.json +++ b/Client/package-lock.json @@ -1759,9 +1759,9 @@ } }, "node_modules/@rollup/rollup-android-arm-eabi": { - "version": "4.18.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.18.1.tgz", - "integrity": "sha512-lncuC4aHicncmbORnx+dUaAgzee9cm/PbIqgWz1PpXuwc+sa1Ct83tnqUDy/GFKleLiN7ZIeytM6KJ4cAn1SxA==", + "version": "4.22.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.22.4.tgz", + "integrity": "sha512-Fxamp4aEZnfPOcGA8KSNEohV8hX7zVHOemC8jVBoBUHu5zpJK/Eu3uJwt6BMgy9fkvzxDaurgj96F/NiLukF2w==", "cpu": [ "arm" ], @@ -1772,9 +1772,9 @@ ] }, "node_modules/@rollup/rollup-android-arm64": { - "version": "4.18.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.18.1.tgz", - "integrity": "sha512-F/tkdw0WSs4ojqz5Ovrw5r9odqzFjb5LIgHdHZG65dFI1lWTWRVy32KDJLKRISHgJvqUeUhdIvy43fX41znyDg==", + "version": "4.22.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.22.4.tgz", + "integrity": "sha512-VXoK5UMrgECLYaMuGuVTOx5kcuap1Jm8g/M83RnCHBKOqvPPmROFJGQaZhGccnsFtfXQ3XYa4/jMCJvZnbJBdA==", "cpu": [ "arm64" ], @@ -1785,9 +1785,9 @@ ] }, "node_modules/@rollup/rollup-darwin-arm64": { - "version": "4.18.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.18.1.tgz", - "integrity": "sha512-vk+ma8iC1ebje/ahpxpnrfVQJibTMyHdWpOGZ3JpQ7Mgn/3QNHmPq7YwjZbIE7km73dH5M1e6MRRsnEBW7v5CQ==", + "version": "4.22.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.22.4.tgz", + "integrity": "sha512-xMM9ORBqu81jyMKCDP+SZDhnX2QEVQzTcC6G18KlTQEzWK8r/oNZtKuZaCcHhnsa6fEeOBionoyl5JsAbE/36Q==", "cpu": [ "arm64" ], @@ -1798,9 +1798,9 @@ ] }, "node_modules/@rollup/rollup-darwin-x64": { - "version": "4.18.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.18.1.tgz", - "integrity": "sha512-IgpzXKauRe1Tafcej9STjSSuG0Ghu/xGYH+qG6JwsAUxXrnkvNHcq/NL6nz1+jzvWAnQkuAJ4uIwGB48K9OCGA==", + "version": "4.22.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.22.4.tgz", + "integrity": "sha512-aJJyYKQwbHuhTUrjWjxEvGnNNBCnmpHDvrb8JFDbeSH3m2XdHcxDd3jthAzvmoI8w/kSjd2y0udT+4okADsZIw==", "cpu": [ "x64" ], @@ -1811,9 +1811,9 @@ ] }, "node_modules/@rollup/rollup-linux-arm-gnueabihf": { - "version": "4.18.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.18.1.tgz", - "integrity": "sha512-P9bSiAUnSSM7EmyRK+e5wgpqai86QOSv8BwvkGjLwYuOpaeomiZWifEos517CwbG+aZl1T4clSE1YqqH2JRs+g==", + "version": "4.22.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.22.4.tgz", + "integrity": "sha512-j63YtCIRAzbO+gC2L9dWXRh5BFetsv0j0va0Wi9epXDgU/XUi5dJKo4USTttVyK7fGw2nPWK0PbAvyliz50SCQ==", "cpu": [ "arm" ], @@ -1824,9 +1824,9 @@ ] }, "node_modules/@rollup/rollup-linux-arm-musleabihf": { - "version": "4.18.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.18.1.tgz", - "integrity": "sha512-5RnjpACoxtS+aWOI1dURKno11d7krfpGDEn19jI8BuWmSBbUC4ytIADfROM1FZrFhQPSoP+KEa3NlEScznBTyQ==", + "version": "4.22.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.22.4.tgz", + "integrity": "sha512-dJnWUgwWBX1YBRsuKKMOlXCzh2Wu1mlHzv20TpqEsfdZLb3WoJW2kIEsGwLkroYf24IrPAvOT/ZQ2OYMV6vlrg==", "cpu": [ "arm" ], @@ -1837,9 +1837,9 @@ ] }, "node_modules/@rollup/rollup-linux-arm64-gnu": { - "version": "4.18.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.18.1.tgz", - "integrity": "sha512-8mwmGD668m8WaGbthrEYZ9CBmPug2QPGWxhJxh/vCgBjro5o96gL04WLlg5BA233OCWLqERy4YUzX3bJGXaJgQ==", + "version": "4.22.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.22.4.tgz", + "integrity": "sha512-AdPRoNi3NKVLolCN/Sp4F4N1d98c4SBnHMKoLuiG6RXgoZ4sllseuGioszumnPGmPM2O7qaAX/IJdeDU8f26Aw==", "cpu": [ "arm64" ], @@ -1850,9 +1850,9 @@ ] }, "node_modules/@rollup/rollup-linux-arm64-musl": { - "version": "4.18.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.18.1.tgz", - "integrity": "sha512-dJX9u4r4bqInMGOAQoGYdwDP8lQiisWb9et+T84l2WXk41yEej8v2iGKodmdKimT8cTAYt0jFb+UEBxnPkbXEQ==", + "version": "4.22.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.22.4.tgz", + "integrity": "sha512-Gl0AxBtDg8uoAn5CCqQDMqAx22Wx22pjDOjBdmG0VIWX3qUBHzYmOKh8KXHL4UpogfJ14G4wk16EQogF+v8hmA==", "cpu": [ "arm64" ], @@ -1863,9 +1863,9 @@ ] }, "node_modules/@rollup/rollup-linux-powerpc64le-gnu": { - "version": "4.18.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-powerpc64le-gnu/-/rollup-linux-powerpc64le-gnu-4.18.1.tgz", - "integrity": "sha512-V72cXdTl4EI0x6FNmho4D502sy7ed+LuVW6Ym8aI6DRQ9hQZdp5sj0a2usYOlqvFBNKQnLQGwmYnujo2HvjCxQ==", + "version": "4.22.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-powerpc64le-gnu/-/rollup-linux-powerpc64le-gnu-4.22.4.tgz", + "integrity": "sha512-3aVCK9xfWW1oGQpTsYJJPF6bfpWfhbRnhdlyhak2ZiyFLDaayz0EP5j9V1RVLAAxlmWKTDfS9wyRyY3hvhPoOg==", "cpu": [ "ppc64" ], @@ -1876,9 +1876,9 @@ ] }, "node_modules/@rollup/rollup-linux-riscv64-gnu": { - "version": "4.18.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.18.1.tgz", - "integrity": "sha512-f+pJih7sxoKmbjghrM2RkWo2WHUW8UbfxIQiWo5yeCaCM0TveMEuAzKJte4QskBp1TIinpnRcxkquY+4WuY/tg==", + "version": "4.22.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.22.4.tgz", + "integrity": "sha512-ePYIir6VYnhgv2C5Xe9u+ico4t8sZWXschR6fMgoPUK31yQu7hTEJb7bCqivHECwIClJfKgE7zYsh1qTP3WHUA==", "cpu": [ "riscv64" ], @@ -1889,9 +1889,9 @@ ] }, "node_modules/@rollup/rollup-linux-s390x-gnu": { - "version": "4.18.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.18.1.tgz", - "integrity": "sha512-qb1hMMT3Fr/Qz1OKovCuUM11MUNLUuHeBC2DPPAWUYYUAOFWaxInaTwTQmc7Fl5La7DShTEpmYwgdt2hG+4TEg==", + "version": "4.22.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.22.4.tgz", + "integrity": "sha512-GqFJ9wLlbB9daxhVlrTe61vJtEY99/xB3C8e4ULVsVfflcpmR6c8UZXjtkMA6FhNONhj2eA5Tk9uAVw5orEs4Q==", "cpu": [ "s390x" ], @@ -1902,9 +1902,9 @@ ] }, "node_modules/@rollup/rollup-linux-x64-gnu": { - "version": "4.18.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.18.1.tgz", - "integrity": "sha512-7O5u/p6oKUFYjRbZkL2FLbwsyoJAjyeXHCU3O4ndvzg2OFO2GinFPSJFGbiwFDaCFc+k7gs9CF243PwdPQFh5g==", + "version": "4.22.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.22.4.tgz", + "integrity": "sha512-87v0ol2sH9GE3cLQLNEy0K/R0pz1nvg76o8M5nhMR0+Q+BBGLnb35P0fVz4CQxHYXaAOhE8HhlkaZfsdUOlHwg==", "cpu": [ "x64" ], @@ -1915,9 +1915,9 @@ ] }, "node_modules/@rollup/rollup-linux-x64-musl": { - "version": "4.18.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.18.1.tgz", - "integrity": "sha512-pDLkYITdYrH/9Cv/Vlj8HppDuLMDUBmgsM0+N+xLtFd18aXgM9Nyqupb/Uw+HeidhfYg2lD6CXvz6CjoVOaKjQ==", + "version": "4.22.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.22.4.tgz", + "integrity": "sha512-UV6FZMUgePDZrFjrNGIWzDo/vABebuXBhJEqrHxrGiU6HikPy0Z3LfdtciIttEUQfuDdCn8fqh7wiFJjCNwO+g==", "cpu": [ "x64" ], @@ -1928,9 +1928,9 @@ ] }, "node_modules/@rollup/rollup-win32-arm64-msvc": { - "version": "4.18.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.18.1.tgz", - "integrity": "sha512-W2ZNI323O/8pJdBGil1oCauuCzmVd9lDmWBBqxYZcOqWD6aWqJtVBQ1dFrF4dYpZPks6F+xCZHfzG5hYlSHZ6g==", + "version": "4.22.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.22.4.tgz", + "integrity": "sha512-BjI+NVVEGAXjGWYHz/vv0pBqfGoUH0IGZ0cICTn7kB9PyjrATSkX+8WkguNjWoj2qSr1im/+tTGRaY+4/PdcQw==", "cpu": [ "arm64" ], @@ -1941,9 +1941,9 @@ ] }, "node_modules/@rollup/rollup-win32-ia32-msvc": { - "version": "4.18.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.18.1.tgz", - "integrity": "sha512-ELfEX1/+eGZYMaCIbK4jqLxO1gyTSOIlZr6pbC4SRYFaSIDVKOnZNMdoZ+ON0mrFDp4+H5MhwNC1H/AhE3zQLg==", + "version": "4.22.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.22.4.tgz", + "integrity": "sha512-SiWG/1TuUdPvYmzmYnmd3IEifzR61Tragkbx9D3+R8mzQqDBz8v+BvZNDlkiTtI9T15KYZhP0ehn3Dld4n9J5g==", "cpu": [ "ia32" ], @@ -1954,9 +1954,9 @@ ] }, "node_modules/@rollup/rollup-win32-x64-msvc": { - "version": "4.18.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.18.1.tgz", - "integrity": "sha512-yjk2MAkQmoaPYCSu35RLJ62+dz358nE83VfTePJRp8CG7aMg25mEJYpXFiD+NcevhX8LxD5OP5tktPXnXN7GDw==", + "version": "4.22.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.22.4.tgz", + "integrity": "sha512-j8pPKp53/lq9lMXN57S8cFz0MynJk8OWNuUnXct/9KCpKU7DgU3bYMJhwWmcqC0UU29p8Lr0/7KEVcaM6bf47Q==", "cpu": [ "x64" ], @@ -5249,9 +5249,9 @@ } }, "node_modules/picocolors": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.0.1.tgz", - "integrity": "sha512-anP1Z8qwhkbmu7MFP5iTt+wQKXgwzf7zTyGlcdzabySa9vd0Xt392U0rVmz9poOaBj0uHJKyyo9/upk0HrEQew==", + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.0.tgz", + "integrity": "sha512-TQ92mBOW0l3LeMeyLV6mzy/kWr8lkd/hp3mTg7wYK7zJhuBStmGMBG0BdeDZS/dZx1IukaX6Bk11zcln25o1Aw==", "license": "ISC" }, "node_modules/picomatch": { @@ -5277,9 +5277,9 @@ } }, "node_modules/postcss": { - "version": "8.4.39", - "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.39.tgz", - "integrity": "sha512-0vzE+lAiG7hZl1/9I8yzKLx3aR9Xbof3fBHKunvMfOCYAtMhrsnccJY2iTURb9EZd5+pLuiNV9/c/GZJOHsgIw==", + "version": "8.4.47", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.47.tgz", + "integrity": "sha512-56rxCq7G/XfB4EkXq9Egn5GCqugWvDFjafDOThIdMBsI15iqPqR5r15TfSr1YPYeEI19YeaXMCbY6u88Y76GLQ==", "funding": [ { "type": "opencollective", @@ -5297,8 +5297,8 @@ "license": "MIT", "dependencies": { "nanoid": "^3.3.7", - "picocolors": "^1.0.1", - "source-map-js": "^1.2.0" + "picocolors": "^1.1.0", + "source-map-js": "^1.2.1" }, "engines": { "node": "^10 || ^12 || >=14" @@ -5678,9 +5678,9 @@ "license": "Unlicense" }, "node_modules/rollup": { - "version": "4.18.1", - "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.18.1.tgz", - "integrity": "sha512-Elx2UT8lzxxOXMpy5HWQGZqkrQOtrVDDa/bm9l10+U4rQnVzbL/LgZ4NOM1MPIDyHk69W4InuYDF5dzRh4Kw1A==", + "version": "4.22.4", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.22.4.tgz", + "integrity": "sha512-vD8HJ5raRcWOyymsR6Z3o6+RzfEPCnVLMFJ6vRslO1jt4LO6dUo5Qnpg7y4RkZFM2DMe3WUirkI5c16onjrc6A==", "license": "MIT", "dependencies": { "@types/estree": "1.0.5" @@ -5693,22 +5693,22 @@ "npm": ">=8.0.0" }, "optionalDependencies": { - "@rollup/rollup-android-arm-eabi": "4.18.1", - "@rollup/rollup-android-arm64": "4.18.1", - "@rollup/rollup-darwin-arm64": "4.18.1", - "@rollup/rollup-darwin-x64": "4.18.1", - "@rollup/rollup-linux-arm-gnueabihf": "4.18.1", - "@rollup/rollup-linux-arm-musleabihf": "4.18.1", - "@rollup/rollup-linux-arm64-gnu": "4.18.1", - "@rollup/rollup-linux-arm64-musl": "4.18.1", - "@rollup/rollup-linux-powerpc64le-gnu": "4.18.1", - "@rollup/rollup-linux-riscv64-gnu": "4.18.1", - "@rollup/rollup-linux-s390x-gnu": "4.18.1", - "@rollup/rollup-linux-x64-gnu": "4.18.1", - "@rollup/rollup-linux-x64-musl": "4.18.1", - "@rollup/rollup-win32-arm64-msvc": "4.18.1", - "@rollup/rollup-win32-ia32-msvc": "4.18.1", - "@rollup/rollup-win32-x64-msvc": "4.18.1", + "@rollup/rollup-android-arm-eabi": "4.22.4", + "@rollup/rollup-android-arm64": "4.22.4", + "@rollup/rollup-darwin-arm64": "4.22.4", + "@rollup/rollup-darwin-x64": "4.22.4", + "@rollup/rollup-linux-arm-gnueabihf": "4.22.4", + "@rollup/rollup-linux-arm-musleabihf": "4.22.4", + "@rollup/rollup-linux-arm64-gnu": "4.22.4", + "@rollup/rollup-linux-arm64-musl": "4.22.4", + "@rollup/rollup-linux-powerpc64le-gnu": "4.22.4", + "@rollup/rollup-linux-riscv64-gnu": "4.22.4", + "@rollup/rollup-linux-s390x-gnu": "4.22.4", + "@rollup/rollup-linux-x64-gnu": "4.22.4", + "@rollup/rollup-linux-x64-musl": "4.22.4", + "@rollup/rollup-win32-arm64-msvc": "4.22.4", + "@rollup/rollup-win32-ia32-msvc": "4.22.4", + "@rollup/rollup-win32-x64-msvc": "4.22.4", "fsevents": "~2.3.2" } }, @@ -5887,9 +5887,9 @@ } }, "node_modules/source-map-js": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.0.tgz", - "integrity": "sha512-itJW8lvSA0TXEphiRoawsCksnlf8SyvmFzIhltqAHluXd88pkCd+cXJVHTDwdCr0IzwptSm035IHQktUu1QUMg==", + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", "license": "BSD-3-Clause", "engines": { "node": ">=0.10.0" @@ -6266,14 +6266,14 @@ } }, "node_modules/vite": { - "version": "5.3.4", - "resolved": "https://registry.npmjs.org/vite/-/vite-5.3.4.tgz", - "integrity": "sha512-Cw+7zL3ZG9/NZBB8C+8QbQZmR54GwqIz+WMI4b3JgdYJvX+ny9AjJXqkGQlDXSXRP9rP0B4tbciRMOVEKulVOA==", + "version": "5.4.8", + "resolved": "https://registry.npmjs.org/vite/-/vite-5.4.8.tgz", + "integrity": "sha512-FqrItQ4DT1NC4zCUqMB4c4AZORMKIa0m8/URVCZ77OZ/QSNeJ54bU1vrFADbDsuwfIPcgknRkmqakQcgnL4GiQ==", "license": "MIT", "dependencies": { "esbuild": "^0.21.3", - "postcss": "^8.4.39", - "rollup": "^4.13.0" + "postcss": "^8.4.43", + "rollup": "^4.20.0" }, "bin": { "vite": "bin/vite.js" @@ -6292,6 +6292,7 @@ "less": "*", "lightningcss": "^1.21.0", "sass": "*", + "sass-embedded": "*", "stylus": "*", "sugarss": "*", "terser": "^5.4.0" @@ -6309,6 +6310,9 @@ "sass": { "optional": true }, + "sass-embedded": { + "optional": true + }, "stylus": { "optional": true }, From 114f4ffb0514a6e14aa8a69ce93d243fec613299 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Mon, 30 Sep 2024 09:52:47 +0800 Subject: [PATCH 75/98] refactor reloadSettings --- Server/controllers/settingsController.js | 4 ++-- Server/service/settingsService.js | 25 +++++++++--------------- 2 files changed, 11 insertions(+), 18 deletions(-) diff --git a/Server/controllers/settingsController.js b/Server/controllers/settingsController.js index c44363bfa..77895caea 100644 --- a/Server/controllers/settingsController.js +++ b/Server/controllers/settingsController.js @@ -31,11 +31,11 @@ const updateAppSettings = async (req, res, next) => { try { const settings = await req.db.updateAppSettings(req.body); - await req.settingsService.reloadSettings(); + const updatedSettings = await req.settingsService.reloadSettings(); return res.status(200).json({ success: true, msg: successMessages.UPDATE_APP_SETTINGS, - data: settings, + data: updatedSettings, }); } catch (error) { error.service === undefined ? (error.service = SERVICE_NAME) : null; diff --git a/Server/service/settingsService.js b/Server/service/settingsService.js index b1027a17c..7cf76f7cc 100644 --- a/Server/service/settingsService.js +++ b/Server/service/settingsService.js @@ -15,6 +15,7 @@ const envConfig = { systemEmailAddress: process.env.SYSTEM_EMAIL_ADDRESS, systemEmailPassword: process.env.SYSTEM_EMAIL_PASSWORD, }; + class SettingsService { constructor() { this.settings = envConfig; @@ -26,11 +27,18 @@ class SettingsService { if (!this.settings) { throw new Error("Settings not found"); } + + // Try to load settings from env first, if not found, load from db for (const key in envConfig) { if (envConfig[key] === undefined && dbSettings[key] !== undefined) { this.settings[key] = dbSettings[key]; } } + + if (!this.settings) { + throw new Error("Settings not found"); + } + return this.settings; } catch (error) { error.service === undefined ? (error.service = SERVICE_NAME) : null; @@ -40,22 +48,7 @@ class SettingsService { } async reloadSettings() { - try { - const dbSettings = await AppSettings.findOne(); - - for (const key in envConfig) { - if (envConfig[key] === undefined && dbSettings[key] !== undefined) { - this.settings[key] = dbSettings[key]; - } - } - if (!this.settings) { - throw new Error("Settings not found"); - } - } catch (error) { - error.service === undefined ? (error.service = SERVICE_NAME) : null; - error.method === undefined ? (error.method = "reloadSettings") : null; - throw error; - } + return this.loadSettings(); } getSettings() { From b6a7cfa7cc87823c2fc1387072b3ca287fde333d Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Mon, 30 Sep 2024 09:56:39 +0800 Subject: [PATCH 76/98] refactor getAppSettings endpoint to user settingsService as source of truth --- Server/controllers/settingsController.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Server/controllers/settingsController.js b/Server/controllers/settingsController.js index 77895caea..e3444436b 100644 --- a/Server/controllers/settingsController.js +++ b/Server/controllers/settingsController.js @@ -4,7 +4,7 @@ const { updateAppSettingsBodyValidation } = require("../validation/joi"); const getAppSettings = async (req, res, next) => { try { - const settings = await req.db.getAppSettings(); + const settings = await req.settingsService.getSettings(); return res.status(200).json({ success: true, msg: successMessages.GET_APP_SETTINGS, @@ -30,7 +30,7 @@ const updateAppSettings = async (req, res, next) => { } try { - const settings = await req.db.updateAppSettings(req.body); + await req.db.updateAppSettings(req.body); const updatedSettings = await req.settingsService.reloadSettings(); return res.status(200).json({ success: true, From 73ac91c2014e7a960619c06972a6b9f11a5ea7d3 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Mon, 30 Sep 2024 10:08:37 +0800 Subject: [PATCH 77/98] Generate random JWT on first account signup if one is not supplied by env --- Server/controllers/authController.js | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Server/controllers/authController.js b/Server/controllers/authController.js index cd9284479..8d41f916b 100644 --- a/Server/controllers/authController.js +++ b/Server/controllers/authController.js @@ -18,6 +18,7 @@ const { errorMessages, successMessages } = require("../utils/messages"); var jwt = require("jsonwebtoken"); const SERVICE_NAME = "AuthController"; const { getTokenFromHeaders } = require("../utils/utils"); +const crypto = require("crypto"); /** * Creates and returns JWT token with an arbitrary payload @@ -61,7 +62,12 @@ const registerController = async (req, res, next) => { const superAdminExists = await req.db.checkSuperadmin(req, res); if (superAdminExists) { await req.db.getInviteTokenAndDelete(inviteToken); + } else { + // This is the first account, create JWT secret to use if one is not supplied by env + const jwtSecret = crypto.randomBytes(64).toString("hex"); + await req.db.updateAppSettings({ jwtSecret }); } + const newUser = await req.db.insertUser({ ...req.body }, req.file); logger.info(successMessages.AUTH_CREATE_USER, { service: SERVICE_NAME, From 6268b2573c560062e8007a56a33514589edd47a9 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Mon, 30 Sep 2024 11:14:53 +0800 Subject: [PATCH 78/98] remove jwtSecret from settings --- Client/src/App.jsx | 2 +- Client/src/Features/Settings/settingsSlice.js | 22 +++------- Client/src/Pages/AdvancedSettings/index.jsx | 43 ++++++++++++++----- Server/controllers/settingsController.js | 6 ++- Server/middleware/verifyJWT.js | 1 - Server/service/settingsService.js | 6 +-- Server/validation/joi.js | 1 - 7 files changed, 47 insertions(+), 34 deletions(-) diff --git a/Client/src/App.jsx b/Client/src/App.jsx index 7bfc630fd..df3e79c80 100644 --- a/Client/src/App.jsx +++ b/Client/src/App.jsx @@ -53,7 +53,7 @@ function App() { const dispatch = useDispatch(); useEffect(() => { - dispatch(getAppSettings(authToken)); + dispatch(getAppSettings({ authToken })); }, [dispatch, authToken]); // Cleanup diff --git a/Client/src/Features/Settings/settingsSlice.js b/Client/src/Features/Settings/settingsSlice.js index 8bec2f87c..ab6a5c746 100644 --- a/Client/src/Features/Settings/settingsSlice.js +++ b/Client/src/Features/Settings/settingsSlice.js @@ -5,26 +5,14 @@ const initialState = { isLoading: false, apiBaseUrl: "http://localhost:5000/api/v1", logLevel: "debug", - clientHost: "http://localhost:5173", - jwtSecret: "my_secret", - dbType: "MongoDB", - dbConnectionString: "mongodb://localhost:27017/uptime_db", - redisHost: "127.0.0.1", - redisPort: 6379, - jwtTTL: "99d", - pagespeedApiKey: "", - systemEmailHost: "smtp.gmail.com", - systemEmailPort: 465, - systemEmailAddress: "", - systemEmailPassword: "", }; export const getAppSettings = createAsyncThunk( "settings/getSettings", - async (authToken, thunkApi) => { + async (data, thunkApi) => { try { const res = await networkService.getAppSettings({ - authToken: authToken, + authToken: data.authToken, }); return res.data; } catch (error) { @@ -83,7 +71,8 @@ const handleGetSettingsFulfilled = (state, action) => { state.isLoading = false; state.success = action.payload.success; state.msg = action.payload.msg; - Object.assign(state, action.payload.data); + state.apiBaseUrl = action.payload.data.apiBaseUrl; + state.logLevel = action.payload.data.logLevel; }; const handleGetSettingsRejected = (state, action) => { state.isLoading = false; @@ -94,7 +83,8 @@ const handleUpdateSettingsFulfilled = (state, action) => { state.isLoading = false; state.success = action.payload.success; state.msg = action.payload.msg; - Object.assign(state, action.payload.data); + state.apiBaseUrl = action.payload.data.apiBaseUrl; + state.logLevel = action.payload.data.logLevel; }; const handleUpdateSettingsRejected = (state, action) => { state.isLoading = false; diff --git a/Client/src/Pages/AdvancedSettings/index.jsx b/Client/src/Pages/AdvancedSettings/index.jsx index 29a9fe53c..38c0a3b12 100644 --- a/Client/src/Pages/AdvancedSettings/index.jsx +++ b/Client/src/Pages/AdvancedSettings/index.jsx @@ -9,7 +9,10 @@ import PropTypes from "prop-types"; import LoadingButton from "@mui/lab/LoadingButton"; import { ConfigBox } from "../Settings/styled"; import { useNavigate } from "react-router"; -import { updateAppSettings } from "../../Features/Settings/settingsSlice"; +import { + getAppSettings, + updateAppSettings, +} from "../../Features/Settings/settingsSlice"; import { useState, useEffect } from "react"; import Select from "../../Components/Inputs/Select"; @@ -26,7 +29,33 @@ const AdvancedSettings = ({ isAdmin }) => { const { authToken } = useSelector((state) => state.auth); const dispatch = useDispatch(); const settings = useSelector((state) => state.settings); - const [localSettings, setLocalSettings] = useState(settings); + const [localSettings, setLocalSettings] = useState({ + apiBaseUrl: "", + logLevel: "debug", + systemEmailHost: "", + systemEmailPort: "", + systemEmailAddress: "", + systemEmailPassword: "", + jwtTTL: "", + dbType: "", + redisHost: "", + redisPort: "", + pagespeedApiKey: "", + }); + + useEffect(() => { + const getSettings = async () => { + const action = await dispatch(getAppSettings({ authToken })); + if (action.payload.success) { + console.log(action.payload.data); + setLocalSettings(action.payload.data); + } else { + createToast({ body: "Failed to get settings" }); + } + }; + getSettings(); + }, [authToken, dispatch]); + const logItems = [ { _id: 1, name: "none" }, { _id: 2, name: "debug" }, @@ -58,6 +87,8 @@ const AdvancedSettings = ({ isAdmin }) => { ); let body = ""; if (action.payload.success) { + console.log(action.payload.data); + setLocalSettings(action.payload.data); body = "Settings saved successfully"; } else { body = "Failed to save settings"; @@ -153,14 +184,6 @@ const AdvancedSettings = ({ isAdmin }) => { - { try { - const settings = await req.settingsService.getSettings(); + const settings = { ...(await req.settingsService.getSettings()) }; + delete settings.jwtSecret; return res.status(200).json({ success: true, msg: successMessages.GET_APP_SETTINGS, @@ -31,7 +32,8 @@ const updateAppSettings = async (req, res, next) => { try { await req.db.updateAppSettings(req.body); - const updatedSettings = await req.settingsService.reloadSettings(); + const updatedSettings = { ...(await req.settingsService.reloadSettings()) }; + delete updatedSettings.jwtSecret; return res.status(200).json({ success: true, msg: successMessages.UPDATE_APP_SETTINGS, diff --git a/Server/middleware/verifyJWT.js b/Server/middleware/verifyJWT.js index ffbcd55a5..0007bad39 100644 --- a/Server/middleware/verifyJWT.js +++ b/Server/middleware/verifyJWT.js @@ -36,7 +36,6 @@ const verifyJWT = (req, res, next) => { const parsedToken = token.slice(TOKEN_PREFIX.length, token.length); // Verify the token's authenticity const { jwtSecret } = req.settingsService.getSettings(); - jwt.verify(parsedToken, jwtSecret, (err, decoded) => { if (err) { return res diff --git a/Server/service/settingsService.js b/Server/service/settingsService.js index 13b19eb6c..752f86607 100644 --- a/Server/service/settingsService.js +++ b/Server/service/settingsService.js @@ -2,6 +2,8 @@ const { env } = require("process"); const AppSettings = require("../models/AppSettings"); const SERVICE_NAME = "SettingsService"; const envConfig = { + logLevel: undefined, + apiBaseUrl: undefined, clientHost: process.env.CLIENT_HOST, jwtSecret: process.env.JWT_SECRET, dbType: process.env.DB_TYPE, @@ -18,7 +20,7 @@ const envConfig = { class SettingsService { constructor() { - this.settings = envConfig; + this.settings = { ...envConfig }; } async loadSettings() { @@ -27,7 +29,6 @@ class SettingsService { if (!this.settings) { throw new Error("Settings not found"); } - // Try to load settings from env first, if not found, load from db for (const key in envConfig) { if (envConfig[key] === undefined && dbSettings[key] !== undefined) { @@ -38,7 +39,6 @@ class SettingsService { if (!this.settings) { throw new Error("Settings not found"); } - return this.settings; } catch (error) { error.service === undefined ? (error.service = SERVICE_NAME) : null; diff --git a/Server/validation/joi.js b/Server/validation/joi.js index 7b26ea8e1..91ba53b94 100644 --- a/Server/validation/joi.js +++ b/Server/validation/joi.js @@ -389,7 +389,6 @@ const updateAppSettingsBodyValidation = joi.object({ apiBaseUrl: joi.string().allow(""), logLevel: joi.string().valid("debug", "none", "error", "warn").allow(""), clientHost: joi.string().allow(""), - jwtSecret: joi.string().allow(""), dbType: joi.string().allow(""), dbConnectionString: joi.string().allow(""), redisHost: joi.string().allow(""), From 9b3085c84d8971cdc59d973a9119e7016d8ed2a1 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Mon, 30 Sep 2024 11:30:52 +0800 Subject: [PATCH 79/98] Add default empty value for pagespeedApiKey in settings --- Client/src/App.jsx | 4 +++- Client/src/Pages/AdvancedSettings/index.jsx | 2 +- Server/models/AppSettings.js | 1 + 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/Client/src/App.jsx b/Client/src/App.jsx index df3e79c80..56c279e78 100644 --- a/Client/src/App.jsx +++ b/Client/src/App.jsx @@ -53,7 +53,9 @@ function App() { const dispatch = useDispatch(); useEffect(() => { - dispatch(getAppSettings({ authToken })); + if (authToken) { + dispatch(getAppSettings({ authToken })); + } }, [dispatch, authToken]); // Cleanup diff --git a/Client/src/Pages/AdvancedSettings/index.jsx b/Client/src/Pages/AdvancedSettings/index.jsx index 38c0a3b12..7609b2578 100644 --- a/Client/src/Pages/AdvancedSettings/index.jsx +++ b/Client/src/Pages/AdvancedSettings/index.jsx @@ -119,7 +119,7 @@ const AdvancedSettings = ({ isAdmin }) => { diff --git a/Server/models/AppSettings.js b/Server/models/AppSettings.js index 79ede650a..f95d58f4b 100644 --- a/Server/models/AppSettings.js +++ b/Server/models/AppSettings.js @@ -48,6 +48,7 @@ const AppSettingsSchema = mongoose.Schema( }, pagespeedApiKey: { type: String, + default: "", }, systemEmailHost: { type: String, From bc85062dd154114ff05aa705d8300724f330f93b Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Mon, 30 Sep 2024 12:24:53 +0800 Subject: [PATCH 80/98] Add docker images and compose for dist --- Docker/dist/build_images.sh | 24 ++++ Docker/dist/client.Dockerfile | 19 +++ .../{quickstart => dist}/docker-compose.yaml | 19 ++- Docker/dist/mongoDB.Dockerfile | 3 + Docker/dist/redis.Dockerfile | 2 + Docker/dist/server.Dockerfile | 13 ++ Docker/docker-compose.yaml | 2 +- Docker/nginx/conf.d/dist_default.conf | 35 +++++ Docker/quickstart/quickstart.sh | 123 ------------------ 9 files changed, 105 insertions(+), 135 deletions(-) create mode 100755 Docker/dist/build_images.sh create mode 100644 Docker/dist/client.Dockerfile rename Docker/{quickstart => dist}/docker-compose.yaml (63%) create mode 100644 Docker/dist/mongoDB.Dockerfile create mode 100644 Docker/dist/redis.Dockerfile create mode 100644 Docker/dist/server.Dockerfile create mode 100644 Docker/nginx/conf.d/dist_default.conf delete mode 100755 Docker/quickstart/quickstart.sh diff --git a/Docker/dist/build_images.sh b/Docker/dist/build_images.sh new file mode 100755 index 000000000..1df514e7e --- /dev/null +++ b/Docker/dist/build_images.sh @@ -0,0 +1,24 @@ + +#!/bin/bash + +# Change directory to root Server directory for correct Docker Context +cd ../.. + +#Client +client="./Docker/dist/client.Dockerfile" + +# MongoDB +mongoDB="./Docker/dist/mongoDB.Dockerfile" + +# Redis +redis="./Docker/dist/redis.Dockerfile" + +# Server +server="./Docker/dist/server.Dockerfile" + +docker build -f $client -t dist_uptime_client . +docker build -f $mongoDB -t dist_uptime_database_mongo . +docker build -f $redis -t dist_uptime_redis . +docker build -f $server -t dist_uptime_server . + +echo "All images built" \ No newline at end of file diff --git a/Docker/dist/client.Dockerfile b/Docker/dist/client.Dockerfile new file mode 100644 index 000000000..46ce12f3c --- /dev/null +++ b/Docker/dist/client.Dockerfile @@ -0,0 +1,19 @@ +FROM node:20-alpine as build + +WORKDIR /app + +COPY ./Client/package*.json ./ + +RUN npm install + +COPY ./Client . + +RUN npm run build + + +FROM nginx:1.27.1-alpine + +COPY ./Docker/nginx/conf.d/dist_default.conf /etc/nginx/conf.d/default.conf +COPY --from=build /app/dist /usr/share/nginx/html + +CMD ["nginx", "-g", "daemon off;"] \ No newline at end of file diff --git a/Docker/quickstart/docker-compose.yaml b/Docker/dist/docker-compose.yaml similarity index 63% rename from Docker/quickstart/docker-compose.yaml rename to Docker/dist/docker-compose.yaml index e2c6e0bae..5a3319b81 100644 --- a/Docker/quickstart/docker-compose.yaml +++ b/Docker/dist/docker-compose.yaml @@ -1,22 +1,21 @@ services: client: - image: bluewaveuptime/uptime_client:latest + image: bluewaveuptime/uptime_client:test ports: - "80:80" - "443:443" depends_on: - server - volumes: - - ./nginx/conf.d:/etc/nginx/conf.d/:ro server: - image: bluewaveuptime/uptime_server:latest + image: bluewaveuptime/uptime_server:test ports: - "5000:5000" - env_file: - - server.env depends_on: - redis - mongodb + environment: + - DB_CONNECTION_STRING=mongodb://mongodb:27017/uptime_db + - REDIS_HOST=redis redis: image: bluewaveuptime/uptime_redis:latest ports: @@ -25,10 +24,8 @@ services: - ./redis/data:/data mongodb: image: bluewaveuptime/uptime_database_mongo:latest - command: ["mongod", "--quiet", "--auth"] - ports: - - "27017:27017" volumes: - ./mongo/data:/data/db - env_file: - - mongo.env + command: ["mongod", "--quiet"] + ports: + - "27017:27017" diff --git a/Docker/dist/mongoDB.Dockerfile b/Docker/dist/mongoDB.Dockerfile new file mode 100644 index 000000000..969a320c2 --- /dev/null +++ b/Docker/dist/mongoDB.Dockerfile @@ -0,0 +1,3 @@ +FROM mongo +EXPOSE 27017 +CMD ["mongod"] diff --git a/Docker/dist/redis.Dockerfile b/Docker/dist/redis.Dockerfile new file mode 100644 index 000000000..af68ec61e --- /dev/null +++ b/Docker/dist/redis.Dockerfile @@ -0,0 +1,2 @@ +FROM redis +EXPOSE 6379 \ No newline at end of file diff --git a/Docker/dist/server.Dockerfile b/Docker/dist/server.Dockerfile new file mode 100644 index 000000000..5d4ea7364 --- /dev/null +++ b/Docker/dist/server.Dockerfile @@ -0,0 +1,13 @@ +FROM node:20-alpine + +WORKDIR /app + +COPY ./Server/package*.json ./ + +RUN npm install + +COPY ./Server/ ./ + +EXPOSE 5000 + +CMD ["node", "index.js"] \ No newline at end of file diff --git a/Docker/docker-compose.yaml b/Docker/docker-compose.yaml index b72b5fc60..fa29a0d4d 100644 --- a/Docker/docker-compose.yaml +++ b/Docker/docker-compose.yaml @@ -40,4 +40,4 @@ services: - ./mongo/data:/data/db - ./mongo/init/create_users.js:/docker-entrypoint-initdb.d/create_users.js env_file: - - mongo.env \ No newline at end of file + - mongo.env diff --git a/Docker/nginx/conf.d/dist_default.conf b/Docker/nginx/conf.d/dist_default.conf new file mode 100644 index 000000000..a3ad90ead --- /dev/null +++ b/Docker/nginx/conf.d/dist_default.conf @@ -0,0 +1,35 @@ +server { + listen 80; + listen [::]:80; + + server_name uptime-demo.bluewavelabs.ca; + server_tokens off; + + location /.well-known/acme-challenge/ { + root /var/www/certbot; + } + + location / { + root /usr/share/nginx/html; + index index.html index.htm; + try_files $uri $uri/ /index.html; + } + + location /api/ { + proxy_pass http://server:5000/api/; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + } + + location /api-docs/ { + proxy_pass http://server:5000/api-docs/; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + } +} \ No newline at end of file diff --git a/Docker/quickstart/quickstart.sh b/Docker/quickstart/quickstart.sh deleted file mode 100755 index b460daaad..000000000 --- a/Docker/quickstart/quickstart.sh +++ /dev/null @@ -1,123 +0,0 @@ -default_server_base_url="http://localhost:5000/api/v1" -default_client_host="http://localhost" -default_jwt_secret="my_secret" -default_db_type="MongoDB" -default_redis_host="redis" -default_redis_port=6379 -default_token_ttl="99d" - -default_db_username="uptime_user" -default_db_password="uptime_password" - -default_system_email_host="smtp.gmail.com" -default_system_email_port=465 - - -echo "Welcome to the Uptime Monitor Setup Script! \n" -echo - -echo "Configuring server" -printf '%*s\n' "${COLUMNS:-$(tput cols)}" '' | tr ' ' '*' -echo - -db_type=$default_db_type -redis_host=$default_redis_host -redis_port=$default_redis_port -jwt_secret=$default_jwt_secret - - -read -p "Enter a username for your database [$default_db_username]: " db_username -db_username="${db_username:-$default_db_username}" - -read -p "Enter a password for your database [$default_db_password]: " db_password -db_password="${db_password:-$default_db_password}" - -read -p "Enter your system email host [$default_system_email_host]: " system_email_host -system_email_host="${system_email_host:-$default_system_email_host}" -echo "System email host: $system_email_host" -echo - -read -p "Enter your DB connection string [$default_db_connection_string]: " db_connection_string -db_connection_string="mongodb://${db_username}:${db_password}@mongodb:27017/uptime_db" -echo "DB connection string: $db_connection_string" -echo - -read -p "Enter your system email port [$default_system_email_port]: " system_email_port -system_email_port="${system_email_port:-$default_system_email_port}" -echo "System email port: $system_email_port" -echo - - -read -p "Enter your system email address: " system_email_address -echo "System email address: $system_email_address" -echo - -read -p "Enter your system email password: " system_email_password -echo "System email password: $system_email_password" -echo - -read -p "Enter your Token TTL [$default_token_ttl]: " token_ttl -token_ttl="${token_ttl:-$default_token_ttl}" -echo "Token TTL: $token_ttl" -echo - -read -p "Enter your Pagespeed API key: " pagespeed_api_key -echo "Pagespeed API key: $pagespeed_api_key" -echo - -echo "Writing to ./server.env" -echo - -{ - echo "CLIENT_HOST=\"$client_host\"" - echo "JWT_SECRET=\"$jwt_secret\"" - echo "DB_TYPE=\"$db_type\"" - echo "DB_CONNECTION_STRING=\"$db_connection_string\"" - echo "REDIS_HOST=\"$redis_host\"" - echo "REDIS_PORT=$redis_port" - echo "SYSTEM_EMAIL_HOST=\"$system_email_host\"" - echo "SYSTEM_EMAIL_PORT=$system_email_port" - echo "SYSTEM_EMAIL_ADDRESS=\"$system_email_address\"" - echo "SYSTEM_EMAIL_PASSWORD=\"$system_email_password\"" - echo "TOKEN_TTL=\"$token_ttl\"" - echo "PAGESPEED_API_KEY=\"$pagespeed_api_key\"" -} > ./server.env - - -echo -{ - echo USERNAME_ENV_VAR=${db_username} - echo PASSWORD_ENV_VAR=${db_password} -} > ./mongo.env - -mkdir -p ./nginx/conf.d/ - - -cat < ./nginx/conf.d/default.conf -server { - listen 80; - listen [::]:80; - - server_name uptime-demo.bluewavelabs.ca; - server_tokens off; - - location /.well-known/acme-challenge/ { - root /var/www/certbot; - } - - location / { - root /usr/share/nginx/html; - index index.html index.htm; - try_files \$uri \$uri/ /index.html; - } - - location /api/ { - proxy_pass http://server:5000/api/; - proxy_http_version 1.1; - proxy_set_header Host \$host; - proxy_set_header X-Real-IP \$remote_addr; - proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for; - proxy_set_header X-Forwarded-Proto \$scheme; - } -} -EOL \ No newline at end of file From c4adb445d604e01aaeef960f6e8ae6e10e5236e1 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Mon, 30 Sep 2024 13:03:41 +0800 Subject: [PATCH 81/98] Update docker-compose dist version to use latest image --- Docker/dist/docker-compose.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Docker/dist/docker-compose.yaml b/Docker/dist/docker-compose.yaml index 5a3319b81..56a7a3c78 100644 --- a/Docker/dist/docker-compose.yaml +++ b/Docker/dist/docker-compose.yaml @@ -1,13 +1,13 @@ services: client: - image: bluewaveuptime/uptime_client:test + image: bluewaveuptime/uptime_client:latest ports: - "80:80" - "443:443" depends_on: - server server: - image: bluewaveuptime/uptime_server:test + image: bluewaveuptime/uptime_server:latest ports: - "5000:5000" depends_on: From 32eff933ca9b87765bb39dd8427b1912da038318 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Mon, 30 Sep 2024 13:30:59 +0800 Subject: [PATCH 82/98] Update readme --- README.md | 139 ++++++++++++++++++------------------------------------ 1 file changed, 45 insertions(+), 94 deletions(-) diff --git a/README.md b/README.md index 6713f209b..7a85e8d0e 100644 --- a/README.md +++ b/README.md @@ -78,123 +78,77 @@ Also check other developer and contributor-friendly projects of BlueWave: - Clone this repository to your local machine -1. [Quickstart for Users](#user-quickstart) -1. [Quickstart for Developers](#dev-quickstart) -1. [Docker Compose](#docker-compose) -1. [Installation (Client)](#client) -1. [Configuration(Client)](#config-client) - - [Environment](#env-vars-client) -1. [Getting Started (Server)](#server) - - [Install Server](#install-server) - - [Environment](#env-vars-server) - - [Database](#databases) - - [(Optional) Dockerised Databases](#optional-docker-databases) - - [Start Server](#start-server) -1. [API Documentation](#api-documentation) -1. [Error Handling](#error-handling) -1. [Contributors](#contributors) +1. [Quickstart for Users](#user-quickstart) +2. [Quickstart for Developers](#dev-quickstart) +3. [Manual Install](#manual-install) + + - [Install Client](#install-client) + - [Environment](#env-vars-client) + - [Start Client](#start-client) + - [Install Server](#install-server) + - [Environment](#env-vars-server) + - [Database](#databases) + - [(Optional) Dockerised Databases](#optional-docker-databases) + - [Start Server](#start-server) + +4. [API Documentation](#api-documentation) +5. [Error Handling](#error-handling) +6. [Contributors](#contributors) --- -#### Quickstart for Users +## Quickstart for Users -1. Download our [Docker Compose File](/Docker/quickstart/docker-compose.yaml) -2. Download our [Quickstart script](/Docker/quickstart/quickstart.sh) -3. Place these files in a directory of your choice -4. Run `quickstart.sh` and generate config files -5. Run `docker compose up` to start the application -6. Application is running at `http://localhost` +1. Download our [Docker Compose File](/Docker/dist/docker-compose.yaml) +2. Run `docker compose up` to start the application +3. Application is running at `http://localhost` -#### Quickstart for Developers +## Quickstart for Developers MAKE SURE YOU CD TO THE SPECIFIED DIRECTORIES AS PATHS IN COMMANDS ARE RELATIVE -##### Cloning and Initial Setup +### Cloning and Initial Setup 1. Clone this repository 2. Checkout the `develop` branch `git checkout develop` -##### Docker Images Setup +### Docker Images Setup 3. CD to the `Docker` directory 4. Run `docker run -d -p 6379:6379 -v $(pwd)/redis/data:/data --name uptime_redis uptime_redis` 5. Run `docker run -d -p 27017:27017 -v $(pwd)/mongo/data:/data/db --name uptime_database_mongo uptime_database_mongo` -##### Server Setup +### Server Setup 6. CD to `Server` directory, run `npm install` 7. While in `Server` directory, create a `.env` file with the [required environmental variables](#env-vars-server) 8. While in the `Server` directory, run `npm run dev` -##### Client Setup +### Client Setup 9. CD to `Client` directory `run npm install` 10. While in the `Client` directory, create a `.env` file with the [required environmental variables](#env-vars-client) 11. While in the `Client` cirectory run `npm run dev` -##### Access Application +### Access Application 12. Client is running at `localhost:5173` 13. Server is running at `localhost:5000` --- -#### Docker Compose +## Manual Install -The fastest way to start the application is to use our Dockerfiles and [Docker Compose](https://docs.docker.com/compose/). +--- -To get the application up and running you need to: - -1. In the `Docker` directory run the build script `build_images.sh` to build docker images for the client, server, Redis database, and MongoDB database. - -2. In the `Dokcer` directory create a `mongo.env` file with a username and password: - -``` -USERNAME_ENV_VAR=user -PASSWORD_ENV_VAR=password -``` - -3. In the `Docker` directory, create a `server.env` file with the [requried environmental variables](#env-vars-server) for the server. Sample file: - -``` -CLIENT_HOST="http://localhost:5173" -JWT_SECRET= -DB_TYPE="MongoDB" -DB_CONNECTION_STRING="mongodb://:@mongodb:27017/uptime_db" -REDIS_HOST="redis" -REDIS_PORT=6379 -TOKEN_TTL="99d" -PAGESPEED_API_KEY= -SYSTEM_EMAIL_HOST="smtp.gmail.com" -SYSTEM_EMAIL_PORT=465 -SYSTEM_EMAIL_ADDRESS= -SYSTEM_EMAIL_PASSWORD= -``` - -4. In the `Client` directory, create a `client.env` file with the [required environmental variables](#env-vars-client) for the client. Sample file: - -``` -VITE_APP_API_BASE_URL="http://localhost:5000/api/v1" -VITE_APP_API_LOG_LEVEL="debug" -``` - -5. In the `Docker` directory run `docker compose up` to run the `docker-compose.yaml` file and start all four images. - -That's it, the application is ready to use on port 80. -
    - -### Client - -#### Installation +### Client Installation 1. Change directory to the `Client` directory 2. Install all dependencies by running `npm install` -
    +--- -#### Configuration - -##### Environmental Variables +### Environmental Variables | ENV Variable Name | Required/Optional | Type | Description | Accepted Values | | --------------------- | ----------------- | --------- | ------------------ | ---------------------------------- | @@ -202,26 +156,22 @@ That's it, the application is ready to use on port 80. | VITE_APP_LOG_LEVEL | Optional | `string` | Log level | `"none"`\|`"error"` \| `"warn"` \| | | VITE_APP_DEMO | Optional | `boolean` | Demo server or not | `true`\|`false` \| | -
    +--- -#### Starting Development Server +### Starting Development Server 1. Run `npm run dev` to start the development server. --- -### Getting Started (Server) - -#### Manual Install - -##### Install Server +### Server Installation 1. Change directory to the `Server` directory 2. Install all dependencies by running `npm install` -
    +--- -##### Environmental Variables +### Environmental Variables Configure the server with the following environmental variables: @@ -242,9 +192,9 @@ Configure the server with the following environmental variables: | SYSTEM_EMAIL_ADDRESS | Required | `string` | System Email Address | | | SYSTEM_EMAIL_PASSWORD | Required | `string` | System Email Password | | -
    +--- -##### Databases +### Databases This project requires two databases: @@ -253,7 +203,7 @@ This project requires two databases: You may use the included Dockerfiles to spin up databases quickly if you wish. -###### (Optional) Dockerised Databases +#### (Optional) Dockerised Databases Dockerfiles for the server and databases are located in the `Docker` directory @@ -282,9 +232,10 @@ From the `Docker` directory run 1. Build the image: `docker build -f redis.Dockerfile -t uptime_redis .` 2. Run the image: `docker run -d -p 6379:6379 -v $(pwd)/redis/data:/data --name uptime_redis uptime_redis`
    -
    -##### Starting the Development Server +--- + +### Starting the Development Server - run `npm run dev` to start the development server @@ -294,15 +245,15 @@ OR --- -#### API Documentation +## API Documentation Our API is documented in accordance with the [OpenAPI spec](https://www.openapis.org/). -You can see the documentation on your local development server at [http://localhost:{port}/api-docs](http://localhost:5000/api-docs) +You can see the documentation on your local development server at [http://localhost:{port}/api-docs](htt>>p://localhost:5000/api-docs) You can also view the documentation on our demo server at [https://uptime-demo.bluewavelabs.ca/api-docs](https://uptime-demo.bluewavelabs.ca/api-docs) -### Error handling +## Error handling Errors are returned in a standard format: From ca30dcc33cdac1199975d4fa15343be006e27eee Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Mon, 30 Sep 2024 14:58:20 +0800 Subject: [PATCH 83/98] set default url to empty string --- Client/src/Features/Settings/settingsSlice.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Client/src/Features/Settings/settingsSlice.js b/Client/src/Features/Settings/settingsSlice.js index ab6a5c746..55509fce7 100644 --- a/Client/src/Features/Settings/settingsSlice.js +++ b/Client/src/Features/Settings/settingsSlice.js @@ -3,7 +3,7 @@ import { createAsyncThunk, createSlice } from "@reduxjs/toolkit"; const initialState = { isLoading: false, - apiBaseUrl: "http://localhost:5000/api/v1", + apiBaseUrl: "", logLevel: "debug", }; From 31509247de097149337f83288427e888bb4c92c0 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Mon, 30 Sep 2024 15:20:10 +0800 Subject: [PATCH 84/98] removed console logs, removed permission check for getting settings --- Client/src/Pages/AdvancedSettings/index.jsx | 1 - Client/src/Utils/NetworkService.js | 4 +++- Server/routes/settingsRoute.js | 2 +- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/Client/src/Pages/AdvancedSettings/index.jsx b/Client/src/Pages/AdvancedSettings/index.jsx index 7609b2578..aa13db0e7 100644 --- a/Client/src/Pages/AdvancedSettings/index.jsx +++ b/Client/src/Pages/AdvancedSettings/index.jsx @@ -47,7 +47,6 @@ const AdvancedSettings = ({ isAdmin }) => { const getSettings = async () => { const action = await dispatch(getAppSettings({ authToken })); if (action.payload.success) { - console.log(action.payload.data); setLocalSettings(action.payload.data); } else { createToast({ body: "Failed to get settings" }); diff --git a/Client/src/Utils/NetworkService.js b/Client/src/Utils/NetworkService.js index 00b52f7f7..7e2a56209 100644 --- a/Client/src/Utils/NetworkService.js +++ b/Client/src/Utils/NetworkService.js @@ -10,7 +10,9 @@ class NetworkService { this.setBaseUrl(baseURL); this.unsubscribe = store.subscribe(() => { const state = store.getState(); - baseURL = state.settings.apiBaseUrl || BASE_URL; + if (state.settings.apiBaseUrl) { + baseURL = state.settings.apiBaseUrl; + } this.setBaseUrl(baseURL); }); this.axiosInstance.interceptors.response.use( diff --git a/Server/routes/settingsRoute.js b/Server/routes/settingsRoute.js index 834f68f26..3cbfff2b8 100644 --- a/Server/routes/settingsRoute.js +++ b/Server/routes/settingsRoute.js @@ -3,7 +3,7 @@ const settingsController = require("../controllers/settingsController"); const { isAllowed } = require("../middleware/isAllowed"); const Monitor = require("../models/Monitor"); -router.get("/", isAllowed(["superadmin"]), settingsController.getAppSettings); +router.get("/", settingsController.getAppSettings); router.put( "/", isAllowed(["superadmin"]), From 53c468f0f307932bd6ee04851e9d3e7b68660f2a Mon Sep 17 00:00:00 2001 From: "Gorkem Cetin (BWL)" <167266851+gorkem-bwl@users.noreply.github.com> Date: Mon, 30 Sep 2024 20:00:51 -0400 Subject: [PATCH 85/98] Update README.md --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 7a85e8d0e..2eebd3a21 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,10 @@ BlueWave Uptime is an open source server monitoring application used to track th See [BlueWave Uptime](https://uptime-demo.bluewavelabs.ca/) in action. The username is uptimedemo@demo.com and the password is Demouser1! +## Questions & Ideas + +We've just launched our [Discussions](https://github.com/bluewave-labs/bluewave-uptime/discussions) page! Feel free to ask questions or share your ideas—we'd love to hear from you! + ## Features - [x] Completely open source, deployable on your servers From f724997b0294dc6206ee377057ab3d4497da9c36 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Tue, 1 Oct 2024 09:55:14 +0800 Subject: [PATCH 86/98] Add JSdocs to SettingsService, add descriptions of services --- Server/index.js | 3 -- Server/service/jobQueue.js | 9 +++++- Server/service/networkService.js | 7 ++++ Server/service/pageSpeedService.js | 52 ------------------------------ Server/service/settingsService.js | 39 +++++++++++++++++----- 5 files changed, 46 insertions(+), 64 deletions(-) delete mode 100644 Server/service/pageSpeedService.js diff --git a/Server/index.js b/Server/index.js index 05eaeb617..b717482cd 100644 --- a/Server/index.js +++ b/Server/index.js @@ -21,7 +21,6 @@ const queueRouter = require("./routes/queueRoute"); const JobQueue = require("./service/jobQueue"); const NetworkService = require("./service/networkService"); const EmailService = require("./service/emailService"); -const PageSpeedService = require("./service/pageSpeedService"); const SettingsService = require("./service/settingsService"); const SERVICE_NAME = "Server"; @@ -73,7 +72,6 @@ const startApp = async () => { req.db = db; req.jobQueue = jobQueue; req.emailService = emailService; - req.pageSpeedService = pageSpeedService; req.settingsService = settingsService; next(); }); @@ -136,7 +134,6 @@ const startApp = async () => { networkService, settingsService ); - const pageSpeedService = new PageSpeedService(); const cleanup = async () => { if (cleaningUp) { diff --git a/Server/service/jobQueue.js b/Server/service/jobQueue.js index 7566debd8..2652a4d53 100644 --- a/Server/service/jobQueue.js +++ b/Server/service/jobQueue.js @@ -5,11 +5,18 @@ const JOBS_PER_WORKER = 5; const logger = require("../utils/logger"); const { errorMessages, successMessages } = require("../utils/messages"); const SERVICE_NAME = "JobQueue"; - +/** + * JobQueue + * + * This service is responsible for managing the job queue. + * It handles enqueuing, dequeuing, and processing jobs. + * It scales the number of workers based on the number of jobs/worker + */ class JobQueue { /** * Constructs a new JobQueue * @constructor + * @param {SettingsService} settingsService - The settings service * @throws {Error} */ constructor(settingsService) { diff --git a/Server/service/networkService.js b/Server/service/networkService.js index b4d90c6e1..f09c7ac70 100644 --- a/Server/service/networkService.js +++ b/Server/service/networkService.js @@ -4,6 +4,13 @@ const logger = require("../utils/logger"); const http = require("http"); const { errorMessages, successMessages } = require("../utils/messages"); +/** + * NetworkService + * + * This service handles all network requests on the back end + * This includes pings, http requests, and pagespeed checks + */ + class NetworkService { constructor(db, emailService) { this.db = db; diff --git a/Server/service/pageSpeedService.js b/Server/service/pageSpeedService.js deleted file mode 100644 index b482e7860..000000000 --- a/Server/service/pageSpeedService.js +++ /dev/null @@ -1,52 +0,0 @@ -const PageSpeedCheck = require("../models/PageSpeedCheck"); -const axios = require("axios"); -const logger = require("../utils/logger"); - -class PageSpeedService { - constructor() { - this.SERVICE_NAME = "PageSpeedService"; - } - - /** - * Runs a PageSpeed check using Google Lighthouse API. - * @param {string} url - The URL to check. - * @returns {Promise} The results from the PageSpeed API. - */ - async runPageSpeedCheck(url) { - try { - const response = await axios.get( - "https://pagespeedonline.googleapis.com/pagespeedonline/v5/runPagespeed?url=https://www.google.com&category=seo&category=accessibility&category=best-practices&category=performance" - ); - - return response.data; - } catch (error) { - logger.error(`Error running PageSpeed check for ${url}`, { - service: this.SERVICE_NAME, - error: error.message, - }); - error.service === undefined ? (error.service = SERVICE_NAME) : null; - error.method === undefined ? (error.method = "runPageSpeedCheck") : null; - throw error; - } - } - - /** - * Creates a new PageSpeedCheck document. - * @param {Object} data - The data for the new PageSpeedCheck. - * @returns {Promise} The created PageSpeedCheck document. - */ - async createPageSpeedCheck(data) { - try { - const newPageSpeedCheck = new PageSpeedCheck(data); - return await newPageSpeedCheck.save(); - } catch (error) { - error.service === undefined ? (error.service = SERVICE_NAME) : null; - error.method === undefined - ? (error.method = "createPageSpeedCheck") - : null; - throw error; - } - } -} - -module.exports = PageSpeedService; diff --git a/Server/service/settingsService.js b/Server/service/settingsService.js index 752f86607..b4769d043 100644 --- a/Server/service/settingsService.js +++ b/Server/service/settingsService.js @@ -1,6 +1,7 @@ -const { env } = require("process"); const AppSettings = require("../models/AppSettings"); const SERVICE_NAME = "SettingsService"; + +// Load settings from environment variables const envConfig = { logLevel: undefined, apiBaseUrl: undefined, @@ -17,19 +18,34 @@ const envConfig = { systemEmailAddress: process.env.SYSTEM_EMAIL_ADDRESS, systemEmailPassword: process.env.SYSTEM_EMAIL_PASSWORD, }; - +/** + * SettingsService + * + * This service is responsible for loading and managing the application settings. + * It gives priority to environment variables and will only load settings + * from the database if they are not set in the environment. + */ class SettingsService { - constructor() { + /** + * Constructs a new SettingsService + * @constructor + * @throws {Error} + */ constructor() { this.settings = { ...envConfig }; } - - async loadSettings() { + /** + * Load settings from the database and merge with environment settings. + * If there are any settings that weren't set by environment variables, use user settings from the database. + * @returns {Promise} The merged settings. + * @throws Will throw an error if settings are not found in the database or if settings have not been loaded. + */ async loadSettings() { try { const dbSettings = await AppSettings.findOne(); if (!this.settings) { throw new Error("Settings not found"); } - // Try to load settings from env first, if not found, load from db + + // If there are any settings that weren't set by environment variables, use user settings from DB for (const key in envConfig) { if (envConfig[key] === undefined && dbSettings[key] !== undefined) { this.settings[key] = dbSettings[key]; @@ -46,11 +62,18 @@ class SettingsService { throw error; } } - + /** + * Reload settings by calling loadSettings. + * @returns {Promise} The reloaded settings. + */ async reloadSettings() { return this.loadSettings(); } - + /** + * Get the current settings. + * @returns {Object} The current settings. + * @throws Will throw an error if settings have not been loaded. + */ getSettings() { if (!this.settings) { throw new Error("Settings have not been loaded"); From 6c598b976f91b5c6b3d24987e8f30ddf8eff42f1 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Tue, 1 Oct 2024 10:01:25 +0800 Subject: [PATCH 87/98] Move db models to db folder --- .gitignore | 3 ++- Server/db/FakeDb.js | 4 ++-- Server/{ => db}/models/AppSettings.js | 0 Server/{ => db}/models/Check.js | 4 ++-- Server/{ => db}/models/InviteToken.js | 0 Server/{ => db}/models/MaintenanceWindow.js | 0 Server/{ => db}/models/Monitor.js | 0 Server/{ => db}/models/Notification.js | 0 Server/{ => db}/models/PageSpeedCheck.js | 0 Server/{ => db}/models/RecoveryToken.js | 0 Server/{ => db}/models/Team.js | 0 Server/{ => db}/models/User.js | 0 Server/db/mongo/MongoDB.js | 4 ++-- Server/db/mongo/modules/checkModule.js | 6 +++--- Server/db/mongo/modules/inviteModule.js | 2 +- Server/db/mongo/modules/maintenaceWindowModule.js | 2 +- Server/db/mongo/modules/monitorModule.js | 8 ++++---- Server/db/mongo/modules/notificationModule.js | 2 +- Server/db/mongo/modules/pageSpeedCheckModule.js | 2 +- Server/db/mongo/modules/recoveryModule.js | 4 ++-- Server/db/mongo/modules/settingsModule.js | 2 +- Server/db/mongo/modules/userModule.js | 4 ++-- Server/middleware/verifyJWT.js | 2 +- Server/routes/authRoute.js | 2 +- Server/routes/checkRoute.js | 2 +- Server/routes/maintenanceWindowRoute.js | 2 +- Server/routes/settingsRoute.js | 2 +- Server/service/pageSpeedService.js | 2 +- Server/service/settingsService.js | 2 +- 29 files changed, 31 insertions(+), 30 deletions(-) rename Server/{ => db}/models/AppSettings.js (100%) rename Server/{ => db}/models/Check.js (93%) rename Server/{ => db}/models/InviteToken.js (100%) rename Server/{ => db}/models/MaintenanceWindow.js (100%) rename Server/{ => db}/models/Monitor.js (100%) rename Server/{ => db}/models/Notification.js (100%) rename Server/{ => db}/models/PageSpeedCheck.js (100%) rename Server/{ => db}/models/RecoveryToken.js (100%) rename Server/{ => db}/models/Team.js (100%) rename Server/{ => db}/models/User.js (100%) diff --git a/.gitignore b/.gitignore index ebf2039ec..a0420fec9 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ .vite .vscode *.sh -!uptime.sh \ No newline at end of file +!uptime.sh +*.idea \ No newline at end of file diff --git a/Server/db/FakeDb.js b/Server/db/FakeDb.js index e4f36d001..a7c8bf4ee 100644 --- a/Server/db/FakeDb.js +++ b/Server/db/FakeDb.js @@ -20,8 +20,8 @@ // The rest of the code is the same, as all the `db` methods are standardized. // ************************** -const Monitor = require("../models/Monitor"); -const UserModel = require("../models/User"); +const Monitor = require("./models/Monitor"); +const UserModel = require("./models/User"); const bcrypt = require("bcrypt"); let FAKE_MONITOR_DATA = []; diff --git a/Server/models/AppSettings.js b/Server/db/models/AppSettings.js similarity index 100% rename from Server/models/AppSettings.js rename to Server/db/models/AppSettings.js diff --git a/Server/models/Check.js b/Server/db/models/Check.js similarity index 93% rename from Server/models/Check.js rename to Server/db/models/Check.js index acb20dfb9..7705ba3fd 100644 --- a/Server/models/Check.js +++ b/Server/db/models/Check.js @@ -1,6 +1,6 @@ const mongoose = require("mongoose"); -const EmailService = require("../service/emailService"); -const Notification = require("../models/Notification"); +const EmailService = require("../../service/emailService"); +const Notification = require("./Notification"); /** * Check Schema for MongoDB collection. diff --git a/Server/models/InviteToken.js b/Server/db/models/InviteToken.js similarity index 100% rename from Server/models/InviteToken.js rename to Server/db/models/InviteToken.js diff --git a/Server/models/MaintenanceWindow.js b/Server/db/models/MaintenanceWindow.js similarity index 100% rename from Server/models/MaintenanceWindow.js rename to Server/db/models/MaintenanceWindow.js diff --git a/Server/models/Monitor.js b/Server/db/models/Monitor.js similarity index 100% rename from Server/models/Monitor.js rename to Server/db/models/Monitor.js diff --git a/Server/models/Notification.js b/Server/db/models/Notification.js similarity index 100% rename from Server/models/Notification.js rename to Server/db/models/Notification.js diff --git a/Server/models/PageSpeedCheck.js b/Server/db/models/PageSpeedCheck.js similarity index 100% rename from Server/models/PageSpeedCheck.js rename to Server/db/models/PageSpeedCheck.js diff --git a/Server/models/RecoveryToken.js b/Server/db/models/RecoveryToken.js similarity index 100% rename from Server/models/RecoveryToken.js rename to Server/db/models/RecoveryToken.js diff --git a/Server/models/Team.js b/Server/db/models/Team.js similarity index 100% rename from Server/models/Team.js rename to Server/db/models/Team.js diff --git a/Server/models/User.js b/Server/db/models/User.js similarity index 100% rename from Server/models/User.js rename to Server/db/models/User.js diff --git a/Server/db/mongo/MongoDB.js b/Server/db/mongo/MongoDB.js index 268e62798..aeb993433 100644 --- a/Server/db/mongo/MongoDB.js +++ b/Server/db/mongo/MongoDB.js @@ -1,6 +1,6 @@ const mongoose = require("mongoose"); -const UserModel = require("../../models/User"); -const AppSettings = require("../../models/AppSettings"); +const UserModel = require("../models/User"); +const AppSettings = require("../models/AppSettings"); //**************************************** // DB Connection diff --git a/Server/db/mongo/modules/checkModule.js b/Server/db/mongo/modules/checkModule.js index c18491021..193d793c6 100644 --- a/Server/db/mongo/modules/checkModule.js +++ b/Server/db/mongo/modules/checkModule.js @@ -1,6 +1,6 @@ -const Check = require("../../../models/Check"); -const Monitor = require("../../../models/Monitor"); -const User = require("../../../models/User"); +const Check = require("../../models/Check"); +const Monitor = require("../../models/Monitor"); +const User = require("../../models/User"); const logger = require("../../../utils/logger"); const SERVICE_NAME = "checkModule"; const dateRangeLookup = { diff --git a/Server/db/mongo/modules/inviteModule.js b/Server/db/mongo/modules/inviteModule.js index 9a0d35621..8152941d7 100644 --- a/Server/db/mongo/modules/inviteModule.js +++ b/Server/db/mongo/modules/inviteModule.js @@ -1,4 +1,4 @@ -const InviteToken = require("../../../models/InviteToken"); +const InviteToken = require("../../models/InviteToken"); const crypto = require("crypto"); const { errorMessages } = require("../../../utils/messages"); const SERVICE_NAME = "inviteModule"; diff --git a/Server/db/mongo/modules/maintenaceWindowModule.js b/Server/db/mongo/modules/maintenaceWindowModule.js index bcb11e816..f49c9dca4 100644 --- a/Server/db/mongo/modules/maintenaceWindowModule.js +++ b/Server/db/mongo/modules/maintenaceWindowModule.js @@ -1,4 +1,4 @@ -const MaintenanceWindow = require("../../../models/MaintenanceWindow"); +const MaintenanceWindow = require("../../models/MaintenanceWindow"); const SERVICE_NAME = "maintenanceWindowModule"; /** diff --git a/Server/db/mongo/modules/monitorModule.js b/Server/db/mongo/modules/monitorModule.js index 002bf9c41..d1fd0d03e 100644 --- a/Server/db/mongo/modules/monitorModule.js +++ b/Server/db/mongo/modules/monitorModule.js @@ -1,8 +1,8 @@ -const Monitor = require("../../../models/Monitor"); -const Check = require("../../../models/Check"); -const PageSpeedCheck = require("../../../models/PageSpeedCheck"); +const Monitor = require("../../models/Monitor"); +const Check = require("../../models/Check"); +const PageSpeedCheck = require("../../models/PageSpeedCheck"); const { errorMessages } = require("../../../utils/messages"); -const Notification = require("../../../models/Notification"); +const Notification = require("../../models/Notification"); const { NormalizeData } = require("../../../utils/dataUtils"); const demoMonitors = require("../../../utils/demoMonitors.json"); const SERVICE_NAME = "monitorModule"; diff --git a/Server/db/mongo/modules/notificationModule.js b/Server/db/mongo/modules/notificationModule.js index 89df2130b..ecc52644d 100644 --- a/Server/db/mongo/modules/notificationModule.js +++ b/Server/db/mongo/modules/notificationModule.js @@ -1,4 +1,4 @@ -const Notification = require("../../../models/Notification"); +const Notification = require("../../models/Notification"); const SERVICE_NAME = "notificationModule"; /** * Creates a new notification. diff --git a/Server/db/mongo/modules/pageSpeedCheckModule.js b/Server/db/mongo/modules/pageSpeedCheckModule.js index 8b76555c5..a0c7694c8 100644 --- a/Server/db/mongo/modules/pageSpeedCheckModule.js +++ b/Server/db/mongo/modules/pageSpeedCheckModule.js @@ -1,4 +1,4 @@ -const PageSpeedCheck = require("../../../models/PageSpeedCheck"); +const PageSpeedCheck = require("../../models/PageSpeedCheck"); const SERVICE_NAME = "pageSpeedCheckModule"; /** * Create a PageSpeed check for a monitor diff --git a/Server/db/mongo/modules/recoveryModule.js b/Server/db/mongo/modules/recoveryModule.js index 469954cef..4649fa084 100644 --- a/Server/db/mongo/modules/recoveryModule.js +++ b/Server/db/mongo/modules/recoveryModule.js @@ -1,5 +1,5 @@ -const UserModel = require("../../../models/User"); -const RecoveryToken = require("../../../models/RecoveryToken"); +const UserModel = require("../../models/User"); +const RecoveryToken = require("../../models/RecoveryToken"); const crypto = require("crypto"); const { errorMessages } = require("../../../utils/messages"); const SERVICE_NAME = "recoveryModule"; diff --git a/Server/db/mongo/modules/settingsModule.js b/Server/db/mongo/modules/settingsModule.js index b7e6b765d..f7cfc9ce1 100644 --- a/Server/db/mongo/modules/settingsModule.js +++ b/Server/db/mongo/modules/settingsModule.js @@ -1,4 +1,4 @@ -const AppSettings = require("../../../models/AppSettings"); +const AppSettings = require("../../models/AppSettings"); const SERVICE_NAME = "SettingsModule"; const getAppSettings = async () => { diff --git a/Server/db/mongo/modules/userModule.js b/Server/db/mongo/modules/userModule.js index bfdd54a4c..c72bd7c5d 100644 --- a/Server/db/mongo/modules/userModule.js +++ b/Server/db/mongo/modules/userModule.js @@ -1,5 +1,5 @@ -const UserModel = require("../../../models/User"); -const TeamModel = require("../../../models/Team"); +const UserModel = require("../../models/User"); +const TeamModel = require("../../models/Team"); const { errorMessages } = require("../../../utils/messages"); const { GenerateAvatarImage } = require("../../../utils/imageProcessing"); diff --git a/Server/middleware/verifyJWT.js b/Server/middleware/verifyJWT.js index 0007bad39..8e2e88b6f 100644 --- a/Server/middleware/verifyJWT.js +++ b/Server/middleware/verifyJWT.js @@ -4,7 +4,7 @@ const SERVICE_NAME = "verifyJWT"; const TOKEN_PREFIX = "Bearer "; const { errorMessages } = require("../utils/messages"); const { parse } = require("path"); -const User = require("../models/User"); +const User = require("../db/models/User"); /** * Verifies the JWT token * @function diff --git a/Server/routes/authRoute.js b/Server/routes/authRoute.js index 362f6a5a2..82628f347 100644 --- a/Server/routes/authRoute.js +++ b/Server/routes/authRoute.js @@ -4,7 +4,7 @@ const { verifyOwnership } = require("../middleware/verifyOwnership"); const { isAllowed } = require("../middleware/isAllowed"); const multer = require("multer"); const upload = multer(); -const User = require("../models/User"); +const User = require("../db/models/User"); const { registerController, diff --git a/Server/routes/checkRoute.js b/Server/routes/checkRoute.js index fe99e7271..47b48809d 100644 --- a/Server/routes/checkRoute.js +++ b/Server/routes/checkRoute.js @@ -2,7 +2,7 @@ const router = require("express").Router(); const checkController = require("../controllers/checkController"); const { verifyOwnership } = require("../middleware/verifyOwnership"); const { isAllowed } = require("../middleware/isAllowed"); -const Monitor = require("../models/Monitor"); +const Monitor = require("../db/models/Monitor"); router.get("/:monitorId", checkController.getChecks); router.post( diff --git a/Server/routes/maintenanceWindowRoute.js b/Server/routes/maintenanceWindowRoute.js index c357df76b..8ed15b609 100644 --- a/Server/routes/maintenanceWindowRoute.js +++ b/Server/routes/maintenanceWindowRoute.js @@ -1,7 +1,7 @@ const router = require("express").Router(); const maintenanceWindowController = require("../controllers/maintenanceWindowController"); const { verifyOwnership } = require("../middleware/verifyOwnership"); -const Monitor = require("../models/Monitor"); +const Monitor = require("../db/models/Monitor"); router.get( "/monitor/:monitorId", diff --git a/Server/routes/settingsRoute.js b/Server/routes/settingsRoute.js index 3cbfff2b8..521987aec 100644 --- a/Server/routes/settingsRoute.js +++ b/Server/routes/settingsRoute.js @@ -1,7 +1,7 @@ const router = require("express").Router(); const settingsController = require("../controllers/settingsController"); const { isAllowed } = require("../middleware/isAllowed"); -const Monitor = require("../models/Monitor"); +const Monitor = require("../db/models/Monitor"); router.get("/", settingsController.getAppSettings); router.put( diff --git a/Server/service/pageSpeedService.js b/Server/service/pageSpeedService.js index b482e7860..189ed46f5 100644 --- a/Server/service/pageSpeedService.js +++ b/Server/service/pageSpeedService.js @@ -1,4 +1,4 @@ -const PageSpeedCheck = require("../models/PageSpeedCheck"); +const PageSpeedCheck = require("../db/models/PageSpeedCheck"); const axios = require("axios"); const logger = require("../utils/logger"); diff --git a/Server/service/settingsService.js b/Server/service/settingsService.js index 752f86607..1a4200a5a 100644 --- a/Server/service/settingsService.js +++ b/Server/service/settingsService.js @@ -1,5 +1,5 @@ const { env } = require("process"); -const AppSettings = require("../models/AppSettings"); +const AppSettings = require("../db/models/AppSettings"); const SERVICE_NAME = "SettingsService"; const envConfig = { logLevel: undefined, From e0e80dc9c7269205cab09d87e0e8aa44886fb611 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Tue, 1 Oct 2024 10:29:32 +0800 Subject: [PATCH 88/98] Refactor method names, add improve JSdocs for monitorController --- Server/controllers/authController.js | 824 +++++++++++------------- Server/controllers/inviteController.js | 4 +- Server/controllers/monitorController.js | 141 ++-- Server/routes/authRoute.js | 36 +- Server/validation/joi.js | 2 +- 5 files changed, 504 insertions(+), 503 deletions(-) diff --git a/Server/controllers/authController.js b/Server/controllers/authController.js index 8d41f916b..31d5c2ec6 100644 --- a/Server/controllers/authController.js +++ b/Server/controllers/authController.js @@ -1,109 +1,103 @@ const express = require("express"); const { - registrationBodyValidation, - loginValidation, - editUserParamValidation, - editUserBodyValidation, - recoveryValidation, - recoveryTokenValidation, - newPasswordValidation, - deleteUserParamValidation, - inviteRoleValidation, - inviteBodyValidation, - inviteVerifciationBodyValidation, + registrationBodyValidation, + loginValidation, + editUserParamValidation, + editUserBodyValidation, + recoveryValidation, + recoveryTokenValidation, + newPasswordValidation, + inviteRoleValidation, + inviteBodyValidation, + inviteVerificationBodyValidation, } = require("../validation/joi"); const logger = require("../utils/logger"); require("dotenv").config(); -const { errorMessages, successMessages } = require("../utils/messages"); -var jwt = require("jsonwebtoken"); +const {errorMessages, successMessages} = require("../utils/messages"); +const jwt = require("jsonwebtoken"); const SERVICE_NAME = "AuthController"; -const { getTokenFromHeaders } = require("../utils/utils"); +const {getTokenFromHeaders} = require("../utils/utils"); const crypto = require("crypto"); /** * Creates and returns JWT token with an arbitrary payload * @function * @param {Object} payload + * @param {Object} appSettings + * @param {function} next * @returns {String} + * @throws {Error} */ -const issueToken = (payload, appSettings) => { - try { - const tokenTTL = appSettings.jwtTTL ? appSettings.jwtTTL : "2h"; - return jwt.sign(payload, appSettings.jwtSecret, { expiresIn: tokenTTL }); - } catch (error) { - error.service === undefined ? (error.service = SERVICE_NAME) : null; - error.method === undefined ? (error.method = "issueToken") : null; - next(error); - } +const issueToken = (payload, appSettings, next) => { + try { + const tokenTTL = appSettings.jwtTTL ? appSettings.jwtTTL : "2h"; + return jwt.sign(payload, appSettings.jwtSecret, {expiresIn: tokenTTL}); + } catch (error) { + error.service === undefined ? (error.service = SERVICE_NAME) : null; + error.method === undefined ? (error.method = "issueToken") : null; + next(error); + } }; /** * @function * @param {express.Request} req * @param {express.Response} res + * @param {function} next * @returns {{success: Boolean, msg: String}} + * @throws {Error} */ -const registerController = async (req, res, next) => { - // joi validation - try { - await registrationBodyValidation.validateAsync(req.body); - } catch (error) { - error.status = 422; - error.service = SERVICE_NAME; - error.message = - error.details?.[0]?.message || error.message || "Validation Error"; - next(error); - return; - } - // Create a new user - try { - const { inviteToken } = req.body; - // If superAdmin exists, a token should be attached to all further register requests - const superAdminExists = await req.db.checkSuperadmin(req, res); - if (superAdminExists) { - await req.db.getInviteTokenAndDelete(inviteToken); - } else { - // This is the first account, create JWT secret to use if one is not supplied by env - const jwtSecret = crypto.randomBytes(64).toString("hex"); - await req.db.updateAppSettings({ jwtSecret }); +const registerUser = async (req, res, next) => { + // joi validation + try { + await registrationBodyValidation.validateAsync(req.body); + } catch (error) { + error.status = 422; + error.service = SERVICE_NAME; + error.message = error.details?.[0]?.message || error.message || "Validation Error"; + next(error); + return; } + // Create a new user + try { + const {inviteToken} = req.body; + // If superAdmin exists, a token should be attached to all further register requests + const superAdminExists = await req.db.checkSuperadmin(req, res); + if (superAdminExists) { + await req.db.getInviteTokenAndDelete(inviteToken); + } else { + // This is the first account, create JWT secret to use if one is not supplied by env + const jwtSecret = crypto.randomBytes(64).toString("hex"); + await req.db.updateAppSettings({jwtSecret}); + } - const newUser = await req.db.insertUser({ ...req.body }, req.file); - logger.info(successMessages.AUTH_CREATE_USER, { - service: SERVICE_NAME, - userId: newUser._id, - }); - - const userForToken = { ...newUser._doc }; - delete userForToken.profileImage; - delete userForToken.avatarImage; - - const appSettings = await req.settingsService.getSettings(); - const token = issueToken(userForToken, appSettings); - req.emailService - .buildAndSendEmail( - "welcomeEmailTemplate", - { name: newUser.firstName }, - newUser.email, - "Welcome to Uptime Monitor" - ) - .catch((error) => { - logger.error("Error sending welcome email", { - service: SERVICE_NAME, - error: error.message, + const newUser = await req.db.insertUser({...req.body}, req.file); + logger.info(successMessages.AUTH_CREATE_USER, { + service: SERVICE_NAME, userId: newUser._id, }); - }); - return res.status(200).json({ - success: true, - msg: successMessages.AUTH_CREATE_USER, - data: { user: newUser, token: token }, - }); - } catch (error) { - error.service === undefined ? (error.service = SERVICE_NAME) : null; - error.method === undefined ? (error.method = "registerController") : null; - next(error); - } + const userForToken = {...newUser._doc}; + delete userForToken.profileImage; + delete userForToken.avatarImage; + + const appSettings = await req.settingsService.getSettings(); + const token = issueToken(userForToken, appSettings); + req.emailService + .buildAndSendEmail("welcomeEmailTemplate", {name: newUser.firstName}, newUser.email, "Welcome to Uptime Monitor") + .catch((error) => { + logger.error("Error sending welcome email", { + service: SERVICE_NAME, error: error.message, + }); + }); + + return res.status(200).json({ + success: true, msg: successMessages.AUTH_CREATE_USER, data: {user: newUser, token: token}, + }); + } catch (error) { + error.service === undefined ? (error.service = SERVICE_NAME) : null; + error.method === undefined ? (error.method = "registerController") : null; + next(error); + } }; /** @@ -111,191 +105,175 @@ const registerController = async (req, res, next) => { * @async * @param {Express.Request} req * @param {Express.Response} res + * @param {function} next * @returns {Promise} */ -const loginController = async (req, res, next) => { - try { - await loginValidation.validateAsync(req.body); - } catch (error) { - error.status = 422; - error.service = SERVICE_NAME; - error.message = - error.details?.[0]?.message || error.message || "Validation Error"; - next(error); - return; - } - try { - const { email, password } = req.body; - // Check if user exists - const user = await req.db.getUserByEmail(email); - - // Compare password - const match = await user.comparePassword(password); - if (match !== true) { - throw new Error(errorMessages.AUTH_INCORRECT_PASSWORD); - } - - // Remove password from user object. Should this be abstracted to DB layer? - const userWithoutPassword = { ...user._doc }; - delete userWithoutPassword.password; - delete userWithoutPassword.avatarImage; - - // Happy path, return token - const appSettings = req.settingsService.getSettings(); - const token = issueToken(userWithoutPassword, appSettings); - // reset avatar image - userWithoutPassword.avatarImage = user.avatarImage; - - return res.status(200).json({ - success: true, - msg: successMessages.AUTH_LOGIN_USER, - data: { user: userWithoutPassword, token: token }, - }); - } catch (error) { - error.status = 500; - error.service === undefined ? (error.service = SERVICE_NAME) : null; - error.method === undefined ? (error.method = "loginController") : null; - next(error); - } -}; - -const userEditController = async (req, res, next) => { - try { - await editUserParamValidation.validateAsync(req.params); - await editUserBodyValidation.validateAsync(req.body); - } catch (error) { - error.status = 422; - error.service = SERVICE_NAME; - error.message = - error.details?.[0]?.message || error.message || "Validation Error"; - next(error); - return; - } - - // TODO is this neccessary any longer? Verify ownership middleware should handle this - if (req.params.userId !== req.user._id.toString()) { - const error = new Error(errorMessages.AUTH_UNAUTHORIZED); - error.status = 401; - error.service = SERVICE_NAME; - next(error); - return; - } - - try { - // Change Password check - if (req.body.password && req.body.newPassword) { - const newPassword = req.body.newPassword; - const password = req.body.password; - - // Compare password - // Get token from headers - const token = getTokenFromHeaders(req.headers); - // Get email from token - const { jwtSecret } = req.settingsService.getSettings(); - const { email } = jwt.verify(token, jwtSecret); - // Add user email to body for DB operation - req.body.email = email; - // Get user - const user = await req.db.getUserByEmail(email); - // Compare passwords - const match = await user.comparePassword(req.body.password); - // If not a match, throw a 403 - if (!match) { - const error = new Error(errorMessages.AUTH_INCORRECT_PASSWORD); - error.status = 403; - throw error; - } - // If a match, update the password - req.body.password = req.body.newPassword; - } - - const updatedUser = await req.db.updateUser(req, res); - return res.status(200).json({ - success: true, - msg: successMessages.AUTH_UPDATE_USER, - data: updatedUser, - }); - } catch (error) { - error.service === undefined ? (error.service = SERVICE_NAME) : null; - error.method === undefined ? (error.method = "userEditController") : null; - next(error); - return; - } -}; - -const inviteController = async (req, res, next) => { - try { - // Only admins can invite - const token = getTokenFromHeaders(req.headers); - const { role, firstname, teamId } = jwt.decode(token); - req.body.teamId = teamId; +const loginUser = async (req, res, next) => { try { - await inviteRoleValidation.validateAsync({ roles: role }); - await inviteBodyValidation.validateAsync(req.body); + await loginValidation.validateAsync(req.body); } catch (error) { - error.status = 422; - error.service = SERVICE_NAME; - error.message = - error.details?.[0]?.message || error.message || "Validation Error"; - next(error); - return; + error.status = 422; + error.service = SERVICE_NAME; + error.message = error.details?.[0]?.message || error.message || "Validation Error"; + next(error); + return; } + try { + const {email, password} = req.body; + // Check if user exists + const user = await req.db.getUserByEmail(email); - const inviteToken = await req.db.requestInviteToken(req, res); - const { clientHost } = req.settingsService.getSettings(); - req.emailService - .buildAndSendEmail( - "employeeActivationTemplate", - { - name: firstname, - link: `${clientHost}/register/${inviteToken.token}`, - }, - req.body.email, - "Welcome to Uptime Monitor" - ) - .catch((error) => { - logger.error("Error sending invite email", { - service: SERVICE_NAME, - error: error.message, + // Compare password + const match = await user.comparePassword(password); + if (match !== true) { + throw new Error(errorMessages.AUTH_INCORRECT_PASSWORD); + } + + // Remove password from user object. Should this be abstracted to DB layer? + const userWithoutPassword = {...user._doc}; + delete userWithoutPassword.password; + delete userWithoutPassword.avatarImage; + + // Happy path, return token + const appSettings = req.settingsService.getSettings(); + const token = issueToken(userWithoutPassword, appSettings); + // reset avatar image + userWithoutPassword.avatarImage = user.avatarImage; + + return res.status(200).json({ + success: true, msg: successMessages.AUTH_LOGIN_USER, data: {user: userWithoutPassword, token: token}, }); - }); - - return res - .status(200) - .json({ success: true, msg: "Invite sent", data: inviteToken }); - } catch (error) { - error.service === undefined ? (error.service = SERVICE_NAME) : null; - error.method === undefined ? (error.method = "inviteController") : null; - next(error); - return; - } + } catch (error) { + error.status = 500; + error.service === undefined ? (error.service = SERVICE_NAME) : null; + error.method === undefined ? (error.method = "loginController") : null; + next(error); + } }; -const inviteVerifyController = async (req, res, next) => { - try { - await inviteVerifciationBodyValidation.validateAsync(req.body); - } catch (error) { - error.status = 422; - error.service = SERVICE_NAME; - error.message = - error.details?.[0]?.message || error.message || "Validation Error"; - next(error); - return; - } +const editUser = async (req, res, next) => { + try { + await editUserParamValidation.validateAsync(req.params); + await editUserBodyValidation.validateAsync(req.body); + } catch (error) { + error.status = 422; + error.service = SERVICE_NAME; + error.message = error.details?.[0]?.message || error.message || "Validation Error"; + next(error); + return; + } - try { - const invite = await req.db.getInviteToken(req, res); - res - .status(200) - .json({ status: "success", msg: "Invite verified", data: invite }); - } catch (error) { - error.service === undefined ? (error.service = SERVICE_NAME) : null; - error.method === undefined - ? (error.method = "inviteVerifyController") - : null; - next(error); - return; - } + // TODO is this neccessary any longer? Verify ownership middleware should handle this + if (req.params.userId !== req.user._id.toString()) { + const error = new Error(errorMessages.AUTH_UNAUTHORIZED); + error.status = 401; + error.service = SERVICE_NAME; + next(error); + return; + } + + try { + // Change Password check + if (req.body.password && req.body.newPassword) { + const newPassword = req.body.newPassword; + const password = req.body.password; + + // Compare password + // Get token from headers + const token = getTokenFromHeaders(req.headers); + // Get email from token + const {jwtSecret} = req.settingsService.getSettings(); + const {email} = jwt.verify(token, jwtSecret); + // Add user email to body for DB operation + req.body.email = email; + // Get user + const user = await req.db.getUserByEmail(email); + // Compare passwords + const match = await user.comparePassword(req.body.password); + // If not a match, throw a 403 + if (!match) { + const error = new Error(errorMessages.AUTH_INCORRECT_PASSWORD); + error.status = 403; + throw error; + } + // If a match, update the password + req.body.password = req.body.newPassword; + } + + const updatedUser = await req.db.updateUser(req, res); + return res.status(200).json({ + success: true, msg: successMessages.AUTH_UPDATE_USER, data: updatedUser, + }); + } catch (error) { + error.service === undefined ? (error.service = SERVICE_NAME) : null; + error.method === undefined ? (error.method = "userEditController") : null; + next(error); + return; + } +}; + +const createInvitation = async (req, res, next) => { + try { + // Only admins can invite + const token = getTokenFromHeaders(req.headers); + const {role, firstname, teamId} = jwt.decode(token); + req.body.teamId = teamId; + try { + await inviteRoleValidation.validateAsync({roles: role}); + await inviteBodyValidation.validateAsync(req.body); + } catch (error) { + error.status = 422; + error.service = SERVICE_NAME; + error.message = error.details?.[0]?.message || error.message || "Validation Error"; + next(error); + return; + } + + const inviteToken = await req.db.requestInviteToken(req, res); + const {clientHost} = req.settingsService.getSettings(); + req.emailService + .buildAndSendEmail("employeeActivationTemplate", { + name: firstname, link: `${clientHost}/register/${inviteToken.token}`, + }, req.body.email, "Welcome to Uptime Monitor") + .catch((error) => { + logger.error("Error sending invite email", { + service: SERVICE_NAME, error: error.message, + }); + }); + + return res + .status(200) + .json({success: true, msg: "Invite sent", data: inviteToken}); + } catch (error) { + error.service === undefined ? (error.service = SERVICE_NAME) : null; + error.method === undefined ? (error.method = "inviteController") : null; + next(error); + return; + } +}; + +const verifyInvitation = async (req, res, next) => { + try { + await inviteVerificationBodyValidation.validateAsync(req.body); + } catch (error) { + error.status = 422; + error.service = SERVICE_NAME; + error.message = error.details?.[0]?.message || error.message || "Validation Error"; + next(error); + return; + } + + try { + const invite = await req.db.getInviteToken(req, res); + res + .status(200) + .json({status: "success", msg: "Invite verified", data: invite}); + } catch (error) { + error.service === undefined ? (error.service = SERVICE_NAME) : null; + error.method === undefined ? (error.method = "inviteVerifyController") : null; + next(error); + return; + } }; /** @@ -306,22 +284,18 @@ const inviteVerifyController = async (req, res, next) => { * @returns {Promise} */ -const checkSuperadminController = async (req, res) => { - try { - const superAdminExists = await req.db.checkSuperadmin(req, res); - return res.status(200).json({ - success: true, - msg: successMessages.AUTH_ADMIN_EXISTS, - data: superAdminExists, - }); - } catch (error) { - error.service === undefined ? (error.service = SERVICE_NAME) : null; - error.method === undefined - ? (error.method = "checkSuperadminController") - : null; - next(error); - return; - } +const checkSuperadminExists = async (req, res) => { + try { + const superAdminExists = await req.db.checkSuperadmin(req, res); + return res.status(200).json({ + success: true, msg: successMessages.AUTH_ADMIN_EXISTS, data: superAdminExists, + }); + } catch (error) { + error.service === undefined ? (error.service = SERVICE_NAME) : null; + error.method === undefined ? (error.method = "checkSuperadminController") : null; + next(error); + return; + } }; /** @@ -333,49 +307,43 @@ const checkSuperadminController = async (req, res) => { * @property {EmailService} req.body.emailService * @returns {Promise} */ -const recoveryRequestController = async (req, res, next) => { - try { - await recoveryValidation.validateAsync(req.body); - } catch (error) { - error.status = 422; - error.service = SERVICE_NAME; - error.message = - error.details?.[0]?.message || error.message || "Validation Error"; - next(error); - return; - } - - try { - const { email } = req.body; - const user = await req.db.getUserByEmail(email); - if (user) { - const recoveryToken = await req.db.requestRecoveryToken(req, res); - const name = user.firstName; - const email = req.body.email; - const { clientHost } = req.settingsService.getSettings(); - const url = `${clientHost}/set-new-password/${recoveryToken.token}`; - - const msgId = await req.emailService.buildAndSendEmail( - "passwordResetTemplate", - { name, email, url }, - email, - "Bluewaves Uptime Password Resest" - ); - - return res.status(200).json({ - success: true, - msg: successMessages.AUTH_CREATE_RECOVERY_TOKEN, - data: msgId, - }); +const requestRecovery = async (req, res, next) => { + try { + await recoveryValidation.validateAsync(req.body); + } catch (error) { + error.status = 422; + error.service = SERVICE_NAME; + error.message = error.details?.[0]?.message || error.message || "Validation Error"; + next(error); + return; + } + + try { + const {email} = req.body; + const user = await req.db.getUserByEmail(email); + if (user) { + const recoveryToken = await req.db.requestRecoveryToken(req, res); + const name = user.firstName; + const email = req.body.email; + const {clientHost} = req.settingsService.getSettings(); + const url = `${clientHost}/set-new-password/${recoveryToken.token}`; + + const msgId = await req.emailService.buildAndSendEmail("passwordResetTemplate", { + name, + email, + url + }, email, "Bluewaves Uptime Password Resest"); + + return res.status(200).json({ + success: true, msg: successMessages.AUTH_CREATE_RECOVERY_TOKEN, data: msgId, + }); + } + } catch (error) { + error.service === undefined ? (error.service = SERVICE_NAME) : null; + error.method === undefined ? (error.method = "recoveryRequestController") : null; + next(error); + return; } - } catch (error) { - error.service === undefined ? (error.service = SERVICE_NAME) : null; - error.method === undefined - ? (error.method = "recoveryRequestController") - : null; - next(error); - return; - } }; /** @@ -387,33 +355,28 @@ const recoveryRequestController = async (req, res, next) => { * @param {Express.Response} res * @returns {Promise} */ -const validateRecoveryTokenController = async (req, res, next) => { - try { - await recoveryTokenValidation.validateAsync(req.body); - } catch (error) { - error.status = 422; - error.service = SERVICE_NAME; - error.message = - error.details?.[0]?.message || error.message || "Validation Error"; - next(error); - return; - } +const validateRecovery = async (req, res, next) => { + try { + await recoveryTokenValidation.validateAsync(req.body); + } catch (error) { + error.status = 422; + error.service = SERVICE_NAME; + error.message = error.details?.[0]?.message || error.message || "Validation Error"; + next(error); + return; + } - try { - await req.db.validateRecoveryToken(req, res); - // TODO Redirect user to reset password after validating token - return res.status(200).json({ - success: true, - msg: successMessages.AUTH_VERIFY_RECOVERY_TOKEN, - }); - } catch (error) { - error.service === undefined ? (error.service = SERVICE_NAME) : null; - error.method === undefined - ? (error.method = "validateRecoveryTokenController") - : null; - next(error); - return; - } + try { + await req.db.validateRecoveryToken(req, res); + return res.status(200).json({ + success: true, msg: successMessages.AUTH_VERIFY_RECOVERY_TOKEN, + }); + } catch (error) { + error.service === undefined ? (error.service = SERVICE_NAME) : null; + error.method === undefined ? (error.method = "validateRecoveryTokenController") : null; + next(error); + return; + } }; /** @@ -426,34 +389,29 @@ const validateRecoveryTokenController = async (req, res, next) => { * @param {Express.Response} res * @returns {Promise} */ -const resetPasswordController = async (req, res, next) => { - try { - await newPasswordValidation.validateAsync(req.body); - } catch (error) { - error.status = 422; - error.service = SERVICE_NAME; - error.message = - error.details?.[0]?.message || error.message || "Validation Error"; - next(error); - return; - } - try { - const user = await req.db.resetPassword(req, res); +const resetPassword = async (req, res, next) => { + try { + await newPasswordValidation.validateAsync(req.body); + } catch (error) { + error.status = 422; + error.service = SERVICE_NAME; + error.message = error.details?.[0]?.message || error.message || "Validation Error"; + next(error); + return; + } + try { + const user = await req.db.resetPassword(req, res); - const appSettings = await req.settingsService.getSettings(); - const token = issueToken(user._doc, appSettings); - res.status(200).json({ - success: true, - msg: successMessages.AUTH_RESET_PASSWORD, - data: { user, token }, - }); - } catch (error) { - error.service === undefined ? (error.service = SERVICE_NAME) : null; - error.method === undefined - ? (error.method = "resetPasswordController") - : null; - next(error); - } + const appSettings = await req.settingsService.getSettings(); + const token = issueToken(user._doc, appSettings); + res.status(200).json({ + success: true, msg: successMessages.AUTH_RESET_PASSWORD, data: {user, token}, + }); + } catch (error) { + error.service === undefined ? (error.service = SERVICE_NAME) : null; + error.method === undefined ? (error.method = "resetPasswordController") : null; + next(error); + } }; /** @@ -465,81 +423,75 @@ const resetPasswordController = async (req, res, next) => { * @returns {Object} The response object with success status and message. * @throws {Error} If user validation fails or user is not found in the database. */ -const deleteUserController = async (req, res, next) => { - try { - const token = getTokenFromHeaders(req.headers); - const decodedToken = jwt.decode(token); - const { _id, email } = decodedToken; +const deleteUser = async (req, res, next) => { + try { + const token = getTokenFromHeaders(req.headers); + const decodedToken = jwt.decode(token); + const {_id, email} = decodedToken; - // Check if the user exists - const user = await req.db.getUserByEmail(email); - if (!user) { - throw new Error(errorMessages.DB_USER_NOT_FOUND); + // Check if the user exists + const user = await req.db.getUserByEmail(email); + if (!user) { + throw new Error(errorMessages.DB_USER_NOT_FOUND); + } + + // 1. Find all the monitors associated with the team ID if superadmin + + const result = await req.db.getMonitorsByTeamId({ + params: {teamId: user.teamId}, + }); + if (user.role.includes("superadmin")) { + //2. Remove all jobs, delete checks and alerts + result?.monitors.length > 0 && (await Promise.all(result.monitors.map(async (monitor) => { + await req.jobQueue.deleteJob(monitor); + await req.db.deleteChecks(monitor._id); + await req.db.deletePageSpeedChecksByMonitorId(monitor._id); + await req.db.deleteNotificationsByMonitorId(monitor._id); + }))); + + // 3. Delete team + await req.db.deleteTeam(user.teamId); + // 4. Delete all other team members + await req.db.deleteAllOtherUsers(); + // 5. Delete each monitor + await req.db.deleteMonitorsByUserId(user._id); + } + // 6. Delete the user by id + await req.db.deleteUser(user._id); + + return res.status(200).json({ + success: true, msg: successMessages.AUTH_DELETE_USER, + }); + } catch (error) { + error.service === undefined ? (error.service = SERVICE_NAME) : null; + error.method === undefined ? (error.method = "deleteUserController") : null; + next(error); } - - // 1. Find all the monitors associated with the team ID if superadmin - - const result = await req.db.getMonitorsByTeamId({ - params: { teamId: user.teamId }, - }); - if (user.role.includes("superadmin")) { - //2. Remove all jobs, delete checks and alerts - result?.monitors.length > 0 && - (await Promise.all( - result.monitors.map(async (monitor) => { - await req.jobQueue.deleteJob(monitor); - await req.db.deleteChecks(monitor._id); - await req.db.deletePageSpeedChecksByMonitorId(monitor._id); - await req.db.deleteNotificationsByMonitorId(monitor._id); - }) - )); - - // 3. Delete team - await req.db.deleteTeam(user.teamId); - // 4. Delete all other team members - await req.db.deleteAllOtherUsers(); - // 5. Delete each monitor - await req.db.deleteMonitorsByUserId(user._id); - } - // 6. Delete the user by id - await req.db.deleteUser(user._id); - - return res.status(200).json({ - success: true, - msg: successMessages.AUTH_DELETE_USER, - }); - } catch (error) { - error.service === undefined ? (error.service = SERVICE_NAME) : null; - error.method === undefined ? (error.method = "deleteUserController") : null; - next(error); - } }; -const getAllUsersController = async (req, res) => { - try { - const allUsers = await req.db.getAllUsers(req, res); - res - .status(200) - .json({ success: true, msg: "Got all users", data: allUsers }); - } catch (error) { - error.service === undefined ? (error.service = SERVICE_NAME) : null; - error.method === undefined - ? (error.method = "getAllUsersController") - : null; - next(error); - } +const getAllUsers = async (req, res) => { + try { + const allUsers = await req.db.getAllUsers(req, res); + res + .status(200) + .json({success: true, msg: "Got all users", data: allUsers}); + } catch (error) { + error.service === undefined ? (error.service = SERVICE_NAME) : null; + error.method === undefined ? (error.method = "getAllUsersController") : null; + next(error); + } }; module.exports = { - registerController, - loginController, - userEditController, - inviteController, - inviteVerifyController, - checkSuperadminController, - recoveryRequestController, - validateRecoveryTokenController, - resetPasswordController, - deleteUserController, - getAllUsersController, + registerUser, + loginUser, + editUser, + createInvitation, + verifyInvitation, + checkSuperadminExists, + requestRecovery, + validateRecovery, + resetPassword, + deleteUser, + getAllUsers, }; diff --git a/Server/controllers/inviteController.js b/Server/controllers/inviteController.js index da9b2496a..a6c198c39 100644 --- a/Server/controllers/inviteController.js +++ b/Server/controllers/inviteController.js @@ -1,7 +1,7 @@ const { inviteRoleValidation, inviteBodyValidation, - inviteVerifciationBodyValidation, + inviteVerificationBodyValidation, } = require("../validation/joi"); const logger = require("../utils/logger"); require("dotenv").config(); @@ -70,7 +70,7 @@ const inviteController = async (req, res, next) => { const inviteVerifyController = async (req, res, next) => { try { - await inviteVerifciationBodyValidation.validateAsync(req.body); + await inviteVerificationBodyValidation.validateAsync(req.body); } catch (error) { error.status = 422; error.service = SERVICE_NAME; diff --git a/Server/controllers/monitorController.js b/Server/controllers/monitorController.js index 5cda56634..3e704a34c 100644 --- a/Server/controllers/monitorController.js +++ b/Server/controllers/monitorController.js @@ -11,8 +11,6 @@ const { getMonitorStatsByIdParamValidation, getMonitorStatsByIdQueryValidation, getCertificateParamValidation, - getMonitorAggregateStatsParamValidation, - getMonitorAggregateStatsQueryValidation, } = require("../validation/joi"); const sslChecker = require("ssl-checker"); @@ -27,6 +25,7 @@ const logger = require("../utils/logger"); * @async * @param {Express.Request} req * @param {Express.Response} res + * @param {function} next * @returns {Promise} * @throws {Error} */ @@ -50,6 +49,7 @@ const getAllMonitors = async (req, res, next) => { * @async * @param {Express.Request} req * @param {Express.Response} res + * @param {function} next * @returns {Promise} * @throws {Error} */ @@ -119,12 +119,15 @@ const getMonitorCertificate = async (req, res, next) => { }; /** - * Returns monitor with matching ID + * Retrieves a monitor by its ID. * @async - * @param {Express.Request} req - * @param {Express.Response} res - * @returns {Promise} - * @throws {Error} + * @param {Object} req - The Express request object. + * @property {Object} req.params - The parameters of the request. + * @property {string} req.params.monitorId - The ID of the monitor to be retrieved. + * @param {Object} res - The Express response object. + * @param {function} next - The next middleware function. + * @returns {Object} The response object with a success status, a message, and the retrieved monitor data. + * @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) => { try { @@ -143,7 +146,6 @@ const getMonitorById = async (req, res, next) => { if (!monitor) { const error = new Error(errorMessages.MONITOR_GET_BY_ID); error.status = 404; - throw error; } return res.json({ @@ -159,14 +161,18 @@ const getMonitorById = async (req, res, next) => { }; /** - * Returns all monitors and a sumamry for a team with TeamID + * Retrieves all monitors and a summary for a team based on the team ID. * @async - * @param {Express.Request} req - * @param {Express.Response} res - * @returns {Promise} - * @throws {Error} + * @param {Object} req - The Express request object. + * @property {Object} req.params - The parameters of the request. + * @property {string} req.params.teamId - The ID of the team. + * @property {Object} req.query - The query parameters of the request. + * @property {string} req.query.type - The type of the request. + * @param {Object} res - The Express response object. + * @param {function} next - The next middleware function. + * @returns {Object} The response object with a success status, a message, and the data containing the monitors and summary for the team. + * @throws {Error} If there is an error during the process, especially if there is a validation error (422). */ - const getMonitorsAndSummaryByTeamId = async (req, res, next) => { try { await getMonitorsAndSummaryByTeamIdParamValidation.validateAsync( @@ -177,8 +183,7 @@ const getMonitorsAndSummaryByTeamId = async (req, res, next) => { } catch (error) { error.status = 422; error.service = SERVICE_NAME; - error.method === undefined && - error.method === "getMonitorsAndSummaryByTeamId"; + error.method === undefined? error.method = "getMonitorsAndSummaryByTeamId": null; error.message = error.details?.[0]?.message || error.message || "Validation Error"; next(error); @@ -207,12 +212,16 @@ const getMonitorsAndSummaryByTeamId = async (req, res, next) => { }; /** - * Returns all monitors belong to team with TeamID + * Retrieves all monitors associated with a team by the team's ID. * @async - * @param {Express.Request} req - * @param {Express.Response} res - * @returns {Promise} - * @throws {Error} + * @param {Object} req - The Express request object. + * @property {Object} req.params - The parameters of the request. + * @property {string} req.params.teamId - The ID of the team. + * @property {Object} req.query - The query parameters of the request. + * @param {Object} res - The Express response object. + * @param {function} next - The next middleware function. + * @returns {Object} The response object with a success status, a message, and the data containing the monitors for the team. + * @throws {Error} If there is an error during the process, especially if there is a validation error (422). */ const getMonitorsByTeamId = async (req, res, next) => { try { @@ -243,14 +252,16 @@ const getMonitorsByTeamId = async (req, res, next) => { }; /** - * Creates a new monitor + * Creates a new monitor and adds it to the job queue. * @async - * @param {Express.Request} req - * @param {Express.Response} res - * @returns {Promise} - * @throws {Error} + * @param {Object} req - The Express request object. + * @property {Object} req.body - The body of the request. + * @property {Array} req.body.notifications - The notifications associated with the monitor. + * @param {Object} res - The Express response object. + * @param {function} next - The next middleware function. + * @returns {Object} The response object with a success status, a message indicating the creation of the monitor, and the created monitor data. + * @throws {Error} If there is an error during the process, especially if there is a validation error (422). */ - const createMonitor = async (req, res, next) => { try { await createMonitorBodyValidation.validateAsync(req.body); @@ -269,13 +280,12 @@ const createMonitor = async (req, res, next) => { const monitor = await req.db.createMonitor(req, res); if (notifications && notifications.length !== 0) { - const setNotifications = await Promise.all( - notifications.map(async (notification) => { - notification.monitorId = monitor._id; - await req.db.createNotification(notification); - }) + monitor.notifications = await Promise.all( + notifications.map(async (notification) => { + notification.monitorId = monitor._id; + await req.db.createNotification(notification); + }) ); - monitor.notifications = setNotifications; await monitor.save(); } // Add monitor to job queue @@ -293,14 +303,16 @@ const createMonitor = async (req, res, next) => { }; /** - * Delete a monitor by ID + * Deletes a monitor by its ID and also deletes associated checks, alerts, and notifications. * @async - * @param {Express.Request} req - * @param {Express.Response} res - * @returns {Promise} - * @throws {Error} + * @param {Object} req - The Express request object. + * @property {Object} req.params - The parameters of the request. + * @property {string} req.params.monitorId - The ID of the monitor to be deleted. + * @param {Object} res - The Express response object. + * @param {function} next - The next middleware function. + * @returns {Object} The response object with a success status and a message indicating the deletion of the monitor. + * @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) => { try { await getMonitorByIdParamValidation.validateAsync(req.params); @@ -331,7 +343,6 @@ const deleteMonitor = async (req, res, next) => { } ); } - return res .status(200) .json({ success: true, msg: successMessages.MONITOR_DELETE }); @@ -342,7 +353,18 @@ const deleteMonitor = async (req, res, next) => { } }; -const deleteAllMonitors = async (req, res) => { +/** + * Deletes all monitors associated with a team. + * @async + * @param {Object} req - The Express request object. + * @property {Object} req.headers - The headers of the request. + * @property {string} req.headers.authorization - The authorization header containing the JWT token. + * @param {Object} res - The Express response object. + * @param {function} next + * @returns {Object} The response object with a success status and a message indicating the number of deleted monitors. + * @throws {Error} If there is an error during the deletion process. + */ +const deleteAllMonitors = async (req, res, next) => { try { const token = getTokenFromHeaders(req.headers); const { jwtSecret } = req.settingsService.getSettings(); @@ -367,12 +389,17 @@ const deleteAllMonitors = async (req, res) => { }; /** - * Edit a monitor by ID + * Edits a monitor by its ID, updates its notifications, and updates its job in the job queue. * @async - * @param {Express.Request} req - * @param {Express.Response} res - * @returns {Promise} - * @throws {Error} + * @param {Object} req - The Express request object. + * @property {Object} req.params - The parameters of the request. + * @property {string} req.params.monitorId - The ID of the monitor to be edited. + * @property {Object} req.body - The body of the request. + * @property {Array} req.body.notifications - The notifications to be associated with the monitor. + * @param {Object} res - The Express response object. + * @param {function} next - The next middleware function. + * @returns {Object} The response object with a success status, a message indicating the editing of the monitor, and the edited monitor data. + * @throws {Error} If there is an error during the process, especially if there is a validation error (422). */ const editMonitor = async (req, res, next) => { try { @@ -423,6 +450,17 @@ const editMonitor = async (req, res, next) => { } }; +/** + * Pauses or resumes a monitor based on its current state. + * @async + * @param {Object} req - The Express request object. + * @property {Object} req.params - The parameters of the request. + * @property {string} req.params.monitorId - The ID of the monitor to be paused or resumed. + * @param {Object} res - The Express response object. + * @param {function} next - The next middleware function. + * @returns {Object} The response object with a success status, a message indicating the new state of the monitor, and the updated monitor data. + * @throws {Error} If there is an error during the process. + */ const pauseMonitor = async (req, res, next) => { try { await pauseMonitorParamValidation.validateAsync(req.params); @@ -458,6 +496,17 @@ const pauseMonitor = async (req, res, next) => { } }; +/** + * Adds demo monitors for a team. + * @async + * @param {Object} req - The Express request object. + * @property {Object} req.headers - The headers of the request. + * @property {string} req.headers.authorization - The authorization header containing the JWT token. + * @param {Object} res - The Express response object. + * @param {function} next - The next middleware function. + * @returns {Object} The response object with a success status, a message indicating the addition of demo monitors, and the number of demo monitors added. + * @throws {Error} If there is an error during the process. + */ const addDemoMonitors = async (req, res, next) => { try { const token = getTokenFromHeaders(req.headers); diff --git a/Server/routes/authRoute.js b/Server/routes/authRoute.js index 82628f347..17d10a5cf 100644 --- a/Server/routes/authRoute.js +++ b/Server/routes/authRoute.js @@ -7,44 +7,44 @@ const upload = multer(); const User = require("../db/models/User"); const { - registerController, - loginController, + registerUser, + loginUser, logoutController, - userEditController, - recoveryRequestController, - validateRecoveryTokenController, - resetPasswordController, - checkSuperadminController, - getAllUsersController, - deleteUserController, + editUser, + requestRecovery, + validateRecovery, + resetPassword, + checkSuperadminExists, + getAllUsers, + deleteUser, } = require("../controllers/authController"); //Auth routes -router.post("/register", upload.single("profileImage"), registerController); -router.post("/login", loginController); +router.post("/register", upload.single("profileImage"), registerUser); +router.post("/login", loginUser); router.put( "/user/:userId", upload.single("profileImage"), verifyJWT, - userEditController + editUser ); -router.get("/users/superadmin", checkSuperadminController); +router.get("/users/superadmin", checkSuperadminExists); router.get( "/users", verifyJWT, isAllowed(["admin", "superadmin"]), - getAllUsersController + getAllUsers ); router.delete( "/user/:userId", verifyJWT, verifyOwnership(User, "userId"), - deleteUserController + deleteUser ); //Recovery routes -router.post("/recovery/request", recoveryRequestController); -router.post("/recovery/validate", validateRecoveryTokenController); -router.post("/recovery/reset/", resetPasswordController); +router.post("/recovery/request", requestRecovery); +router.post("/recovery/validate", validateRecovery); +router.post("/recovery/reset/", resetPassword); module.exports = router; diff --git a/Server/validation/joi.js b/Server/validation/joi.js index 91ba53b94..1af324008 100644 --- a/Server/validation/joi.js +++ b/Server/validation/joi.js @@ -410,7 +410,7 @@ module.exports = { newPasswordValidation, inviteRoleValidation, inviteBodyValidation, - inviteVerifciationBodyValidation, + inviteVerificationBodyValidation: inviteVerifciationBodyValidation, createMonitorBodyValidation, getMonitorByIdParamValidation, getMonitorByIdQueryValidation, From c1d1e0ad1d06f1f36833bf7285817e7d9ca44126 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Tue, 1 Oct 2024 10:55:51 +0800 Subject: [PATCH 89/98] Refactor for clarity and correctness, add JS docs --- Server/controllers/authController.js | 199 +++++++----------- Server/controllers/inviteController.js | 168 ++++++++------- .../maintenanceWindowController.js | 7 +- Server/controllers/monitorController.js | 4 +- Server/db/mongo/modules/monitorModule.js | 6 +- Server/routes/authRoute.js | 1 - Server/utils/messages.js | 13 +- 7 files changed, 180 insertions(+), 218 deletions(-) diff --git a/Server/controllers/authController.js b/Server/controllers/authController.js index 31d5c2ec6..f3ad6fba4 100644 --- a/Server/controllers/authController.js +++ b/Server/controllers/authController.js @@ -1,4 +1,3 @@ -const express = require("express"); const { registrationBodyValidation, loginValidation, @@ -7,9 +6,6 @@ const { recoveryValidation, recoveryTokenValidation, newPasswordValidation, - inviteRoleValidation, - inviteBodyValidation, - inviteVerificationBodyValidation, } = require("../validation/joi"); const logger = require("../utils/logger"); require("dotenv").config(); @@ -24,28 +20,31 @@ const crypto = require("crypto"); * @function * @param {Object} payload * @param {Object} appSettings - * @param {function} next * @returns {String} * @throws {Error} */ -const issueToken = (payload, appSettings, next) => { +const issueToken = (payload, appSettings) => { try { const tokenTTL = appSettings.jwtTTL ? appSettings.jwtTTL : "2h"; return jwt.sign(payload, appSettings.jwtSecret, {expiresIn: tokenTTL}); } catch (error) { error.service === undefined ? (error.service = SERVICE_NAME) : null; error.method === undefined ? (error.method = "issueToken") : null; - next(error); + throw error; } }; /** - * @function - * @param {express.Request} req - * @param {express.Response} res - * @param {function} next - * @returns {{success: Boolean, msg: String}} - * @throws {Error} + * Registers a new user. If the user is the first account, a JWT secret is created. If not, an invite token is required. + * @async + * @param {Object} req - The Express request object. + * @property {Object} req.body - The body of the request. + * @property {string} req.body.inviteToken - The invite token for registration. + * @property {Object} req.file - The file object for the user's profile image. + * @param {Object} res - The Express response object. + * @param {function} next - The next middleware function. + * @returns {Object} The response object with a success status, a message indicating the creation of the user, the created user data, and a JWT token. + * @throws {Error} If there is an error during the process, especially if there is a validation error (422). */ const registerUser = async (req, res, next) => { // joi validation @@ -101,12 +100,16 @@ const registerUser = async (req, res, next) => { }; /** - * Returns JWT with User info + * Logs in a user by validating the user's credentials and issuing a JWT token. * @async - * @param {Express.Request} req - * @param {Express.Response} res - * @param {function} next - * @returns {Promise} + * @param {Object} req - The Express request object. + * @property {Object} req.body - The body of the request. + * @property {string} req.body.email - The email of the user. + * @property {string} req.body.password - The password of the user. + * @param {Object} res - The Express response object. + * @param {function} next - The next middleware function. + * @returns {Object} The response object with a success status, a message indicating the login of the user, the user data (without password and avatar image), and a JWT token. + * @throws {Error} If there is an error during the process, especially if there is a validation error (422) or the password is incorrect. */ const loginUser = async (req, res, next) => { try { @@ -126,7 +129,8 @@ const loginUser = async (req, res, next) => { // Compare password const match = await user.comparePassword(password); if (match !== true) { - throw new Error(errorMessages.AUTH_INCORRECT_PASSWORD); + next(new Error(errorMessages.AUTH_INCORRECT_PASSWORD)); + return; } // Remove password from user object. Should this be abstracted to DB layer? @@ -151,6 +155,20 @@ const loginUser = async (req, res, next) => { } }; +/** + * Edits a user's information. If the user wants to change their password, the current password is checked before updating to the new password. + * @async + * @param {Object} req - The Express request object. + * @property {Object} req.params - The parameters of the request. + * @property {string} req.params.userId - The ID of the user to be edited. + * @property {Object} req.body - The body of the request. + * @property {string} req.body.password - The current password of the user. + * @property {string} req.body.newPassword - The new password of the user. + * @param {Object} res - The Express response object. + * @param {function} next - The next middleware function. + * @returns {Object} The response object with a success status, a message indicating the update of the user, and the updated user data. + * @throws {Error} If there is an error during the process, especially if there is a validation error (422), the user is unauthorized (401), or the password is incorrect (403). + */ const editUser = async (req, res, next) => { try { await editUserParamValidation.validateAsync(req.params); @@ -175,10 +193,6 @@ const editUser = async (req, res, next) => { try { // Change Password check if (req.body.password && req.body.newPassword) { - const newPassword = req.body.newPassword; - const password = req.body.password; - - // Compare password // Get token from headers const token = getTokenFromHeaders(req.headers); // Get email from token @@ -194,7 +208,8 @@ const editUser = async (req, res, next) => { if (!match) { const error = new Error(errorMessages.AUTH_INCORRECT_PASSWORD); error.status = 403; - throw error; + next(error) + return; } // If a match, update the password req.body.password = req.body.newPassword; @@ -208,83 +223,19 @@ const editUser = async (req, res, next) => { error.service === undefined ? (error.service = SERVICE_NAME) : null; error.method === undefined ? (error.method = "userEditController") : null; next(error); - return; - } -}; - -const createInvitation = async (req, res, next) => { - try { - // Only admins can invite - const token = getTokenFromHeaders(req.headers); - const {role, firstname, teamId} = jwt.decode(token); - req.body.teamId = teamId; - try { - await inviteRoleValidation.validateAsync({roles: role}); - await inviteBodyValidation.validateAsync(req.body); - } catch (error) { - error.status = 422; - error.service = SERVICE_NAME; - error.message = error.details?.[0]?.message || error.message || "Validation Error"; - next(error); - return; - } - - const inviteToken = await req.db.requestInviteToken(req, res); - const {clientHost} = req.settingsService.getSettings(); - req.emailService - .buildAndSendEmail("employeeActivationTemplate", { - name: firstname, link: `${clientHost}/register/${inviteToken.token}`, - }, req.body.email, "Welcome to Uptime Monitor") - .catch((error) => { - logger.error("Error sending invite email", { - service: SERVICE_NAME, error: error.message, - }); - }); - - return res - .status(200) - .json({success: true, msg: "Invite sent", data: inviteToken}); - } catch (error) { - error.service === undefined ? (error.service = SERVICE_NAME) : null; - error.method === undefined ? (error.method = "inviteController") : null; - next(error); - return; - } -}; - -const verifyInvitation = async (req, res, next) => { - try { - await inviteVerificationBodyValidation.validateAsync(req.body); - } catch (error) { - error.status = 422; - error.service = SERVICE_NAME; - error.message = error.details?.[0]?.message || error.message || "Validation Error"; - next(error); - return; - } - - try { - const invite = await req.db.getInviteToken(req, res); - res - .status(200) - .json({status: "success", msg: "Invite verified", data: invite}); - } catch (error) { - error.service === undefined ? (error.service = SERVICE_NAME) : null; - error.method === undefined ? (error.method = "inviteVerifyController") : null; - next(error); - return; } }; /** - * Checks to see if an admin account exists + * Checks if a superadmin account exists in the database. * @async - * @param {Express.Request} req - * @param {Express.Response} res - * @returns {Promise} + * @param {Object} req - The Express request object. + * @param {Object} res - The Express response object. + * @param {function} next - The next middleware function. + * @returns {Object} The response object with a success status, a message indicating the existence of a superadmin, and a boolean indicating the existence of a superadmin. + * @throws {Error} If there is an error during the process. */ - -const checkSuperadminExists = async (req, res) => { +const checkSuperAdminExists = async (req, res, next) => { try { const superAdminExists = await req.db.checkSuperadmin(req, res); return res.status(200).json({ @@ -294,18 +245,19 @@ const checkSuperadminExists = async (req, res) => { error.service === undefined ? (error.service = SERVICE_NAME) : null; error.method === undefined ? (error.method = "checkSuperadminController") : null; next(error); - return; } }; /** - * Returns a recovery token + * Requests a recovery token for a user. The user's email is validated and a recovery token is created and sent via email. * @async - * @param {Express.Request} req - * @property {Object} req.body - * @property {string} req.body.email - * @property {EmailService} req.body.emailService - * @returns {Promise} + * @param {Object} req - The Express request object. + * @property {Object} req.body - The body of the request. + * @property {string} req.body.email - The email of the user requesting recovery. + * @param {Object} res - The Express response object. + * @param {function} next - The next middleware function. + * @returns {Object} The response object with a success status, a message indicating the creation of the recovery token, and the message ID of the sent email. + * @throws {Error} If there is an error during the process, especially if there is a validation error (422). */ const requestRecovery = async (req, res, next) => { try { @@ -332,7 +284,7 @@ const requestRecovery = async (req, res, next) => { name, email, url - }, email, "Bluewaves Uptime Password Resest"); + }, email, "Bluewave Uptime Password Reset"); return res.status(200).json({ success: true, msg: successMessages.AUTH_CREATE_RECOVERY_TOKEN, data: msgId, @@ -342,18 +294,19 @@ const requestRecovery = async (req, res, next) => { error.service === undefined ? (error.service = SERVICE_NAME) : null; error.method === undefined ? (error.method = "recoveryRequestController") : null; next(error); - return; } }; /** - * Returns a recovery token + * Validates a recovery token. The recovery token is validated and if valid, a success message is returned. * @async - * @param {Express.Request} req - * @property {Object} req.body - * @property {string} req.body.token - * @param {Express.Response} res - * @returns {Promise} + * @param {Object} req - The Express request object. + * @property {Object} req.body - The body of the request. + * @property {string} req.body.token - The recovery token to be validated. + * @param {Object} res - The Express response object. + * @param {function} next - The next middleware function. + * @returns {Object} The response object with a success status and a message indicating the validation of the recovery token. + * @throws {Error} If there is an error during the process, especially if there is a validation error (422). */ const validateRecovery = async (req, res, next) => { try { @@ -375,19 +328,20 @@ const validateRecovery = async (req, res, next) => { error.service === undefined ? (error.service = SERVICE_NAME) : null; error.method === undefined ? (error.method = "validateRecoveryTokenController") : null; next(error); - return; } }; /** - * Returns an updated user + * Resets a user's password. The new password is validated and if valid, the user's password is updated in the database and a new JWT token is issued. * @async - * @param {Express.Request} req - * @property {Object} req.body - * @property {string} req.body.token - * @property {string} req.body.password - * @param {Express.Response} res - * @returns {Promise} + * @param {Object} req - The Express request object. + * @property {Object} req.body - The body of the request. + * @property {string} req.body.token - The recovery token. + * @property {string} req.body.password - The new password of the user. + * @param {Object} res - The Express response object. + * @param {function} next - The next middleware function. + * @returns {Object} The response object with a success status, a message indicating the reset of the password, the updated user data (without password and avatar image), and a new JWT token. + * @throws {Error} If there is an error during the process, especially if there is a validation error (422). */ const resetPassword = async (req, res, next) => { try { @@ -427,12 +381,13 @@ const deleteUser = async (req, res, next) => { try { const token = getTokenFromHeaders(req.headers); const decodedToken = jwt.decode(token); - const {_id, email} = decodedToken; + const {email} = decodedToken; // Check if the user exists const user = await req.db.getUserByEmail(email); if (!user) { - throw new Error(errorMessages.DB_USER_NOT_FOUND); + next(new Error(errorMessages.DB_USER_NOT_FOUND)); + return; } // 1. Find all the monitors associated with the team ID if superadmin @@ -486,9 +441,7 @@ module.exports = { registerUser, loginUser, editUser, - createInvitation, - verifyInvitation, - checkSuperadminExists, + checkSuperadminExists: checkSuperAdminExists, requestRecovery, validateRecovery, resetPassword, diff --git a/Server/controllers/inviteController.js b/Server/controllers/inviteController.js index a6c198c39..9863f9666 100644 --- a/Server/controllers/inviteController.js +++ b/Server/controllers/inviteController.js @@ -1,101 +1,111 @@ const { - inviteRoleValidation, - inviteBodyValidation, - inviteVerificationBodyValidation, + inviteRoleValidation, + inviteBodyValidation, + inviteVerificationBodyValidation, } = require("../validation/joi"); const logger = require("../utils/logger"); require("dotenv").config(); -const { errorMessages, successMessages } = require("../utils/messages"); -var jwt = require("jsonwebtoken"); +const jwt = require("jsonwebtoken"); const SERVICE_NAME = "inviteController"; const getTokenFromHeaders = (headers) => { - const authorizationHeader = headers.authorization; - if (!authorizationHeader) throw new Error("No auth headers"); + const authorizationHeader = headers.authorization; + if (!authorizationHeader) throw new Error("No auth headers"); - const parts = authorizationHeader.split(" "); - if (parts.length !== 2 || parts[0] !== "Bearer") - throw new Error("Invalid auth headers"); + const parts = authorizationHeader.split(" "); + if (parts.length !== 2 || parts[0] !== "Bearer") + throw new Error("Invalid auth headers"); - return parts[1]; + return parts[1]; }; -const inviteController = async (req, res, next) => { - try { - // Only admins can invite - const token = getTokenFromHeaders(req.headers); - const { role, firstname, teamId } = jwt.decode(token); - req.body.teamId = teamId; +/** + * Issues an invitation to a new user. Only admins can invite new users. An invitation token is created and sent via email. + * @async + * @param {Object} req - The Express request object. + * @property {Object} req.headers - The headers of the request. + * @property {string} req.headers.authorization - The authorization header containing the JWT token. + * @property {Object} req.body - The body of the request. + * @property {string} req.body.email - The email of the user to be invited. + * @param {Object} res - The Express response object. + * @param {function} next - The next middleware function. + * @returns {Object} The response object with a success status, a message indicating the sending of the invitation, and the invitation token. + * @throws {Error} If there is an error during the process, especially if there is a validation error (422). + */ +const issueInvitation = async (req, res, next) => { try { - await inviteRoleValidation.validateAsync({ roles: role }); - await inviteBodyValidation.validateAsync(req.body); + // Only admins can invite + const token = getTokenFromHeaders(req.headers); + const {role, firstname, teamId} = jwt.decode(token); + req.body.teamId = teamId; + try { + await inviteRoleValidation.validateAsync({roles: role}); + await inviteBodyValidation.validateAsync(req.body); + } catch (error) { + error.status = 422; + error.service = SERVICE_NAME; + error.message = + error.details?.[0]?.message || error.message || "Validation Error"; + next(error); + return; + } + + const inviteToken = await req.db.requestInviteToken({...req.body}); + const {clientHost} = req.settingsService.getSettings(); + req.emailService + .buildAndSendEmail( + "employeeActivationTemplate", + { + name: firstname, + link: `${clientHost}/register/${inviteToken.token}`, + }, + req.body.email, + "Welcome to Uptime Monitor" + ) + .catch((error) => { + logger.error("Error sending invite email", { + service: SERVICE_NAME, + error: error.message, + }); + }); + + return res + .status(200) + .json({success: true, msg: "Invite sent", data: inviteToken}); } catch (error) { - error.status = 422; - error.service = SERVICE_NAME; - error.message = - error.details?.[0]?.message || error.message || "Validation Error"; - next(error); - return; + error.service === undefined ? (error.service = SERVICE_NAME) : null; + error.method === undefined ? (error.method = "inviteController") : null; + next(error); } - - const inviteToken = await req.db.requestInviteToken({ ...req.body }); - const { clientHost } = req.settingsService.getSettings(); - req.emailService - .buildAndSendEmail( - "employeeActivationTemplate", - { - name: firstname, - link: `${clientHost}/register/${inviteToken.token}`, - }, - req.body.email, - "Welcome to Uptime Monitor" - ) - .catch((error) => { - logger.error("Error sending invite email", { - service: SERVICE_NAME, - error: error.message, - }); - }); - - return res - .status(200) - .json({ success: true, msg: "Invite sent", data: inviteToken }); - } catch (error) { - error.service === undefined ? (error.service = SERVICE_NAME) : null; - error.method === undefined ? (error.method = "inviteController") : null; - next(error); - return; - } }; const inviteVerifyController = async (req, res, next) => { - try { - await inviteVerificationBodyValidation.validateAsync(req.body); - } catch (error) { - error.status = 422; - error.service = SERVICE_NAME; - error.message = - error.details?.[0]?.message || error.message || "Validation Error"; - next(error); - return; - } + try { + await inviteVerificationBodyValidation.validateAsync(req.body); + } catch (error) { + error.status = 422; + error.service = SERVICE_NAME; + error.message = + error.details?.[0]?.message || error.message || "Validation Error"; + next(error); + return; + } - try { - const invite = await req.db.getInviteToken(req.body.token); - res - .status(200) - .json({ status: "success", msg: "Invite verified", data: invite }); - } catch (error) { - error.service === undefined ? (error.service = SERVICE_NAME) : null; - error.method === undefined - ? (error.method = "inviteVerifyController") - : null; - next(error); - return; - } + try { + const invite = await req.db.getInviteToken(req.body.token); + res + .status(200) + .json({status: "success", msg: "Invite verified", data: invite}); + } catch (error) { + error.service === undefined ? (error.service = SERVICE_NAME) : null; + error.method === undefined + ? (error.method = "inviteVerifyController") + : null; + next(error); + } }; module.exports = { - inviteController, - inviteVerifyController, + inviteController: issueInvitation, + inviteVerifyController, }; diff --git a/Server/controllers/maintenanceWindowController.js b/Server/controllers/maintenanceWindowController.js index 755d4c5bb..775c04728 100644 --- a/Server/controllers/maintenanceWindowController.js +++ b/Server/controllers/maintenanceWindowController.js @@ -5,8 +5,9 @@ const { getMaintenanceWindowsByMonitorIdParamValidation, } = require("../validation/joi"); +const {successMessages} = require("../utils/messages") + const SERVICE_NAME = "maintenanceWindowController"; -const { errorMessages, successMessages } = require("../utils/messages"); const createMaintenanceWindow = async (req, res, next) => { try { @@ -67,7 +68,7 @@ const getMaintenanceWindowsByUserId = async (req, res, next) => { return res.status(201).json({ success: true, - msg: successMessages.MAINTEANCE_WINDOW_GET_BY_USER, + msg: successMessages.MAINTENANCE_WINDOW_GET_BY_USER, data: maintenanceWindows, }); } catch (error) { @@ -100,7 +101,7 @@ const getMaintenanceWindowsByMonitorId = async (req, res, next) => { return res.status(201).json({ success: true, - msg: successMessages.MAINTEANCE_WINDOW_GET_BY_USER, + msg: successMessages.MAINTENANCE_WINDOW_GET_BY_USER, data: maintenanceWindows, }); } catch (error) { diff --git a/Server/controllers/monitorController.js b/Server/controllers/monitorController.js index 3e704a34c..3f77a412e 100644 --- a/Server/controllers/monitorController.js +++ b/Server/controllers/monitorController.js @@ -69,7 +69,7 @@ const getMonitorStatsById = async (req, res, next) => { const monitorStats = await req.db.getMonitorStatsById(req); return res.json({ success: true, - msg: successMessages.MONTIOR_STATS_BY_ID, + msg: successMessages.MONITOR_STATS_BY_ID, data: monitorStats, }); } catch (error) { @@ -150,7 +150,7 @@ const getMonitorById = async (req, res, next) => { return res.json({ success: true, - msg: successMessages.MONTIOR_GET_BY_ID, + msg: successMessages.MONITOR_GET_BY_ID, data: monitor, }); } catch (error) { diff --git a/Server/db/mongo/modules/monitorModule.js b/Server/db/mongo/modules/monitorModule.js index d1fd0d03e..bac2e146b 100644 --- a/Server/db/mongo/modules/monitorModule.js +++ b/Server/db/mongo/modules/monitorModule.js @@ -147,7 +147,7 @@ const getMonitorStatsById = async (req) => { let { limit, sortOrder, dateRange, numToDisplay, normalize } = req.query; const monitor = await Monitor.findById(monitorId); if (monitor === null || monitor === undefined) { - throw new Error(errorMessages.DB_FIND_MONTIOR_BY_ID(monitorId)); + throw new Error(errorMessages.DB_FIND_MONITOR_BY_ID(monitorId)); } // This effectively removes limit, returning all checks if (limit === undefined) limit = 0; @@ -283,7 +283,7 @@ const getMonitorById = async (monitorId) => { try { const monitor = await Monitor.findById(monitorId); if (monitor === null || monitor === undefined) { - throw new Error(errorMessages.DB_FIND_MONTIOR_BY_ID(monitorId)); + throw new Error(errorMessages.DB_FIND_MONITOR_BY_ID(monitorId)); } // Get notifications const notifications = await Notification.find({ @@ -481,7 +481,7 @@ const deleteMonitor = async (req, res) => { try { const monitor = await Monitor.findByIdAndDelete(monitorId); if (!monitor) { - throw new Error(errorMessages.DB_FIND_MONTIOR_BY_ID(monitorId)); + throw new Error(errorMessages.DB_FIND_MONITOR_BY_ID(monitorId)); } return monitor; } catch (error) { diff --git a/Server/routes/authRoute.js b/Server/routes/authRoute.js index 17d10a5cf..ce6ec440e 100644 --- a/Server/routes/authRoute.js +++ b/Server/routes/authRoute.js @@ -9,7 +9,6 @@ const User = require("../db/models/User"); const { registerUser, loginUser, - logoutController, editUser, requestRecovery, validateRecovery, diff --git a/Server/utils/messages.js b/Server/utils/messages.js index 59fa53f49..c1e4d887b 100644 --- a/Server/utils/messages.js +++ b/Server/utils/messages.js @@ -13,7 +13,7 @@ const errorMessages = { NO_AUTH_TOKEN: "No auth token provided", INVALID_AUTH_TOKEN: "Invalid auth token", - //Onwership Middleware + //Ownership Middleware VERIFY_OWNER_NOT_FOUND: "Document not found", VERIFY_OWNER_UNAUTHORIZED: "Unauthorized access", @@ -26,17 +26,16 @@ const errorMessages = { DB_TOKEN_NOT_FOUND: "Token not found", DB_RESET_PASSWORD_BAD_MATCH: "New password must be different from old password", - DB_FIND_MONTIOR_BY_ID: (monitorId) => + DB_FIND_MONITOR_BY_ID: (monitorId) => `Monitor with id ${monitorId} not found`, DB_DELETE_CHECKS: (monitorId) => `No checks found for monitor with id ${monitorId}`, - DB_DELETE_ALERT: (alertId) => `Alert with id ${alertId} not found`, //Auth errors AUTH_INCORRECT_PASSWORD: "Incorrect password", AUTH_UNAUTHORIZED: "Unauthorized access", - // Monitor Errros + // Monitor Errors MONITOR_GET_BY_ID: "Monitor not found", MONITOR_GET_BY_USER_ID: "No monitors found for user", @@ -77,8 +76,8 @@ const successMessages = { //Monitor Controller MONITOR_GET_ALL: "Got all monitors successfully", - MONTIOR_STATS_BY_ID: "Got monitor stats by Id successfully", - MONTIOR_GET_BY_ID: "Got monitor by Id successfully", + MONITOR_STATS_BY_ID: "Got monitor stats by Id successfully", + MONITOR_GET_BY_ID: "Got monitor by Id successfully", MONITOR_GET_BY_USER_ID: (userId) => `Got monitor for ${userId} successfully"`, MONITOR_CREATE: "Monitor created successfully", MONITOR_DELETE: "Monitor deleted successfully", @@ -94,7 +93,7 @@ const successMessages = { //Maintenance Window Controller MAINTENANCE_WINDOW_CREATE: "Maintenance Window created successfully", - MAINTEANCE_WINDOW_GET_BY_USER: "Got Maintenance Windows by User successfully", + MAINTENANCE_WINDOW_GET_BY_USER: "Got Maintenance Windows by User successfully", //Ping Operations PING_SUCCESS: "Success", From d507f5e7fee3ec4e75e57e5474fd31372c086a80 Mon Sep 17 00:00:00 2001 From: "Gorkem Cetin (BWL)" <167266851+gorkem-bwl@users.noreply.github.com> Date: Mon, 30 Sep 2024 23:09:35 -0400 Subject: [PATCH 90/98] Fix cases --- Client/src/Pages/Settings/index.jsx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Client/src/Pages/Settings/index.jsx b/Client/src/Pages/Settings/index.jsx index bf8cfcc79..9aba1c792 100644 --- a/Client/src/Pages/Settings/index.jsx +++ b/Client/src/Pages/Settings/index.jsx @@ -164,7 +164,7 @@ const Settings = ({ isAdmin }) => { > - General Settings + General settings Display timezone- The timezone of the dashboard you publicly display. @@ -218,7 +218,7 @@ const Settings = ({ isAdmin }) => { {isAdmin && ( - Demo Monitors + Demo monitors Here you can add and remove demo monitors @@ -254,7 +254,7 @@ const Settings = ({ isAdmin }) => { {isAdmin && ( - Advanced Settings + Advanced settings Click here to modify advanced settings From fc84d8e986710d46e655e213aed66be303e8b068 Mon Sep 17 00:00:00 2001 From: "Gorkem Cetin (BWL)" <167266851+gorkem-bwl@users.noreply.github.com> Date: Mon, 30 Sep 2024 23:13:30 -0400 Subject: [PATCH 91/98] Fix cases --- Client/src/Pages/AdvancedSettings/index.jsx | 32 ++++++++++----------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/Client/src/Pages/AdvancedSettings/index.jsx b/Client/src/Pages/AdvancedSettings/index.jsx index aa13db0e7..6af21cc31 100644 --- a/Client/src/Pages/AdvancedSettings/index.jsx +++ b/Client/src/Pages/AdvancedSettings/index.jsx @@ -110,9 +110,9 @@ const AdvancedSettings = ({ isAdmin }) => { > - Client Settings + Client settings - Modify client settings here + Modify client settings here. @@ -124,7 +124,7 @@ const AdvancedSettings = ({ isAdmin }) => { />