Merge branch 'develop' into feat/be/job-queue-tests

This commit is contained in:
Alex Holliday committed 2024-10-23 10:07:09 +08:00
commit 2eea17110c
23 files changed
+943 -891

No files matched your search

+1
View File
@@ -14,5 +14,6 @@ module.exports = {
rules: { rules: {
"react/jsx-no-target-blank": "off", "react/jsx-no-target-blank": "off",
"react-refresh/only-export-components": ["warn", { allowConstantExport: true }], "react-refresh/only-export-components": ["warn", { allowConstantExport: true }],
"react/no-unescaped-entities": "off",
}, },
}; };
+30 -30
View File
@@ -20,8 +20,8 @@
"@reduxjs/toolkit": "2.2.5", "@reduxjs/toolkit": "2.2.5",
"axios": "^1.7.4", "axios": "^1.7.4",
"chart.js": "^4.4.3", "chart.js": "^4.4.3",
"dayjs": "1.11.11", "dayjs": "1.11.13",
"joi": "17.13.1", "joi": "17.13.3",
"jwt-decode": "^4.0.0", "jwt-decode": "^4.0.0",
"react": "^18.2.0", "react": "^18.2.0",
"react-dom": "^18.2.0", "react-dom": "^18.2.0",
@@ -29,7 +29,7 @@
"react-router": "^6.23.0", "react-router": "^6.23.0",
"react-router-dom": "^6.23.1", "react-router-dom": "^6.23.1",
"react-toastify": "^10.0.5", "react-toastify": "^10.0.5",
"recharts": "2.13.0-alpha.4", "recharts": "2.13.0",
"redux-persist": "6.0.0", "redux-persist": "6.0.0",
"vite-plugin-svgr": "^4.2.0" "vite-plugin-svgr": "^4.2.0"
}, },
@@ -2304,9 +2304,9 @@
"license": "MIT" "license": "MIT"
}, },
"node_modules/@types/react": { "node_modules/@types/react": {
"version": "18.3.3", "version": "18.3.11",
"resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.3.tgz", "resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.11.tgz",
"integrity": "sha512-hti/R0pS0q1/xx+TsI73XIqk26eBsISZ2R0wUijXIngRK9R/e7Xw/cXVxQK7R5JjW+SV4zGcn5hXjudkN/pLIw==", "integrity": "sha512-r6QZ069rFTjrEYgFdOck1gK7FLVsgJE7tTz0pQBczlBNUhBNk0MQH4UbnFSwjpQLMkLzgqvBBa+qGpLje16eTQ==",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@types/prop-types": "*", "@types/prop-types": "*",
@@ -2314,9 +2314,9 @@
} }
}, },
"node_modules/@types/react-dom": { "node_modules/@types/react-dom": {
"version": "18.3.0", "version": "18.3.1",
"resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-18.3.0.tgz", "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-18.3.1.tgz",
"integrity": "sha512-EhwApuTmMBmXuFOikhQLIBUn6uFg81SwLMOAUgodJF14SOBOCMdU04gDoYi0WOJJHD144TL32z4yDqCW3dnkQg==", "integrity": "sha512-qW1Mfv8taImTthu4KoXgDfLuk4bydU6Q/TkADnDWWHwi4NX4BR+LWfTp2sVmTqRrsHvyDDTelgelxJ+SsejKKQ==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
@@ -2606,9 +2606,9 @@
} }
}, },
"node_modules/axios": { "node_modules/axios": {
"version": "1.7.4", "version": "1.7.7",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.7.4.tgz", "resolved": "https://registry.npmjs.org/axios/-/axios-1.7.7.tgz",
"integrity": "sha512-DukmaFRnY6AzAALSH4J2M3k6PkaC+MfaAGdEERRWcC9q3/TWQwLpHR8ZRLKTdQ3aBDL64EdluRDjJqKw+BPZEw==", "integrity": "sha512-S4kL7XrjgBmvdGut0sN3yJxqYzrDOnivkBiN0OFs6hLiUam3UPvswUo0kqGyhqUZGEOytHyumEdXsAkgCOUf3Q==",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"follow-redirects": "^1.15.6", "follow-redirects": "^1.15.6",
@@ -2766,9 +2766,9 @@
} }
}, },
"node_modules/chart.js": { "node_modules/chart.js": {
"version": "4.4.3", "version": "4.4.5",
"resolved": "https://registry.npmjs.org/chart.js/-/chart.js-4.4.3.tgz", "resolved": "https://registry.npmjs.org/chart.js/-/chart.js-4.4.5.tgz",
"integrity": "sha512-qK1gkGSRYcJzqrrzdR6a+I0vQ4/R+SoODXyAjscQ/4mzuNzySaMCd+hyVxitSY1+L2fjPD1Gbn+ibNqRmwQeLw==", "integrity": "sha512-CVVjg1RYTJV9OCC8WeJPMx8gsV8K6WIyIEQUE3ui4AR9Hfgls9URri6Ja3hyMVBbTF8Q2KFa19PE815gWcWhng==",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@kurkle/color": "^0.3.0" "@kurkle/color": "^0.3.0"
@@ -3051,9 +3051,9 @@
} }
}, },
"node_modules/dayjs": { "node_modules/dayjs": {
"version": "1.11.11", "version": "1.11.13",
"resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.11.11.tgz", "resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.11.13.tgz",
"integrity": "sha512-okzr3f11N6WuqYtZSvm+F776mB41wRZMhKP+hc34YdW+KmtYYK9iqvHSwo2k9FEH3fhGXvOPV6yz2IcSrfRUDg==", "integrity": "sha512-oaMBel6gjolK862uaPQOVTA7q3TZhuSvuMQAAglQDOWYO9A91IrAOUJEyKVlqJlHE0vq5p5UXxzdPfMH/x6xNg==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/debug": { "node_modules/debug": {
@@ -4686,9 +4686,9 @@
} }
}, },
"node_modules/joi": { "node_modules/joi": {
"version": "17.13.1", "version": "17.13.3",
"resolved": "https://registry.npmjs.org/joi/-/joi-17.13.1.tgz", "resolved": "https://registry.npmjs.org/joi/-/joi-17.13.3.tgz",
"integrity": "sha512-vaBlIKCyo4FCUtCm7Eu4QZd/q02bWcxfUO6YSXAZOWF6gzcLBeba8kwotUdYJjDLW8Cz8RywsSOqiNJZW0mNvg==", "integrity": "sha512-otDA4ldcIx+ZXsKHWmp0YizCweVRZG96J10b0FevjfuncLO1oX59THoAmHkNubYJ+9gWsYsp5k8v4ib6oDv1fA==",
"license": "BSD-3-Clause", "license": "BSD-3-Clause",
"dependencies": { "dependencies": {
"@hapi/hoek": "^9.3.0", "@hapi/hoek": "^9.3.0",
@@ -5448,9 +5448,9 @@
} }
}, },
"node_modules/react-toastify": { "node_modules/react-toastify": {
"version": "10.0.5", "version": "10.0.6",
"resolved": "https://registry.npmjs.org/react-toastify/-/react-toastify-10.0.5.tgz", "resolved": "https://registry.npmjs.org/react-toastify/-/react-toastify-10.0.6.tgz",
"integrity": "sha512-mNKt2jBXJg4O7pSdbNUfDdTsK9FIdikfsIE/yUCxbAEXl4HMyJaivrVFcn3Elvt5xvCQYhUZm+hqTIu1UXM3Pw==", "integrity": "sha512-yYjp+omCDf9lhZcrZHKbSq7YMuK0zcYkDFTzfRFgTXkTFHZ1ToxwAonzA4JI5CxA91JpjFLmwEsZEgfYfOqI1A==",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"clsx": "^2.1.0" "clsx": "^2.1.0"
@@ -5477,9 +5477,9 @@
} }
}, },
"node_modules/recharts": { "node_modules/recharts": {
"version": "2.13.0-alpha.4", "version": "2.13.0",
"resolved": "https://registry.npmjs.org/recharts/-/recharts-2.13.0-alpha.4.tgz", "resolved": "https://registry.npmjs.org/recharts/-/recharts-2.13.0.tgz",
"integrity": "sha512-K9naL6F7pEcDYJE6yFQASSCQecSLPP0JagnvQ9hPtA/aHgsxsnIOjouLP5yrFZehxzfCkV5TEORr7/uNtSr7Qw==", "integrity": "sha512-sbfxjWQ+oLWSZEWmvbq/DFVdeRLqqA6d0CDjKx2PkxVVdoXo16jvENCE+u/x7HxOO+/fwx//nYRwb8p8X6s/lQ==",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"clsx": "^2.0.0", "clsx": "^2.0.0",
@@ -6234,9 +6234,9 @@
} }
}, },
"node_modules/vite": { "node_modules/vite": {
"version": "5.4.8", "version": "5.4.9",
"resolved": "https://registry.npmjs.org/vite/-/vite-5.4.8.tgz", "resolved": "https://registry.npmjs.org/vite/-/vite-5.4.9.tgz",
"integrity": "sha512-FqrItQ4DT1NC4zCUqMB4c4AZORMKIa0m8/URVCZ77OZ/QSNeJ54bU1vrFADbDsuwfIPcgknRkmqakQcgnL4GiQ==", "integrity": "sha512-20OVpJHh0PAM0oSOELa5GaZNWeDjcAvQjGXy2Uyr+Tp+/D2/Hdz6NLgpJLsarPTA2QJ6v8mX2P1ZfbsSKvdMkg==",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"esbuild": "^0.21.3", "esbuild": "^0.21.3",
+3 -3
View File
@@ -22,8 +22,8 @@
"@reduxjs/toolkit": "2.2.5", "@reduxjs/toolkit": "2.2.5",
"axios": "^1.7.4", "axios": "^1.7.4",
"chart.js": "^4.4.3", "chart.js": "^4.4.3",
"dayjs": "1.11.11", "dayjs": "1.11.13",
"joi": "17.13.1", "joi": "17.13.3",
"jwt-decode": "^4.0.0", "jwt-decode": "^4.0.0",
"react": "^18.2.0", "react": "^18.2.0",
"react-dom": "^18.2.0", "react-dom": "^18.2.0",
@@ -31,7 +31,7 @@
"react-router": "^6.23.0", "react-router": "^6.23.0",
"react-router-dom": "^6.23.1", "react-router-dom": "^6.23.1",
"react-toastify": "^10.0.5", "react-toastify": "^10.0.5",
"recharts": "2.13.0-alpha.4", "recharts": "2.13.0",
"redux-persist": "6.0.0", "redux-persist": "6.0.0",
"vite-plugin-svgr": "^4.2.0" "vite-plugin-svgr": "^4.2.0"
}, },
@@ -0,0 +1,67 @@
import { useId } from "react";
import PropTypes from "prop-types";
import { Modal, Stack, Typography } from "@mui/material";
const GenericDialog = ({ title, description, open, onClose, theme, children }) => {
const titleId = useId();
const descriptionId = useId();
const ariaDescribedBy = description?.length > 0 ? descriptionId : "";
return (
<Modal
aria-labelledby={titleId}
aria-describedby={ariaDescribedBy}
open={open}
onClose={onClose}
>
<Stack
gap={theme.spacing(2)}
sx={{
position: "absolute",
top: "50%",
left: "50%",
transform: "translate(-50%, -50%)",
width: 400,
bgcolor: theme.palette.background.main,
border: 1,
borderColor: theme.palette.border.light,
borderRadius: theme.shape.borderRadius,
boxShadow: 24,
p: theme.spacing(15),
"&:focus": {
outline: "none",
},
}}
>
<Typography
id={titleId}
component="h2"
fontSize={16}
color={theme.palette.text.primary}
fontWeight={600}
>
{title}
</Typography>
{description && (
<Typography
id={descriptionId}
color={theme.palette.text.tertiary}
>
{description}
</Typography>
)}
{children}
</Stack>
</Modal>
);
};
GenericDialog.propTypes = {
title: PropTypes.string.isRequired,
description: PropTypes.string,
open: PropTypes.bool.isRequired,
onClose: PropTypes.func.isRequired,
theme: PropTypes.object.isRequired,
children: PropTypes.element.isRequired,
};
export { GenericDialog };
+25 -66
View File
@@ -1,63 +1,26 @@
import LoadingButton from "@mui/lab/LoadingButton";
import { Button, Modal, Stack, Typography } from "@mui/material";
import PropTypes from "prop-types"; import PropTypes from "prop-types";
import LoadingButton from "@mui/lab/LoadingButton";
import { Button, Stack } from "@mui/material";
import { GenericDialog } from "./genericDialog";
const Dialog = ({ const Dialog = ({
modelTitle,
modelDescription,
open,
onClose,
title, title,
confirmationBtnLbl,
confirmationBtnOnClick,
cancelBtnLbl,
cancelBtnOnClick,
theme,
isLoading,
description, description,
open,
theme,
onCancel,
confirmationButtonLabel,
onConfirm,
isLoading,
}) => { }) => {
return ( return (
<Modal <GenericDialog
aria-labelledby={modelTitle} title={title}
aria-describedby={modelDescription} description={description}
open={open} open={open}
onClose={onClose} onClose={onCancel}
theme={theme}
> >
<Stack
gap={theme.spacing(2)}
sx={{
position: "absolute",
top: "50%",
left: "50%",
transform: "translate(-50%, -50%)",
width: 400,
bgcolor: theme.palette.background.main,
border: 1,
borderColor: theme.palette.border.light,
borderRadius: theme.shape.borderRadius,
boxShadow: 24,
p: theme.spacing(15),
"&:focus": {
outline: "none",
},
}}
>
<Typography
id={modelTitle}
component="h2"
fontSize={16}
color={theme.palette.text.primary}
fontWeight={600}
>
{title}
</Typography>
{description && (
<Typography
id={modelDescription}
color={theme.palette.text.tertiary}
>
{description}
</Typography>
)}
<Stack <Stack
direction="row" direction="row"
gap={theme.spacing(4)} gap={theme.spacing(4)}
@@ -67,37 +30,33 @@ const Dialog = ({
<Button <Button
variant="text" variant="text"
color="info" color="info"
onClick={cancelBtnOnClick} onClick={onCancel}
> >
{cancelBtnLbl} Cancel
</Button> </Button>
<LoadingButton <LoadingButton
variant="contained" variant="contained"
color="error" color="error"
loading={isLoading} loading={isLoading}
onClick={confirmationBtnOnClick} onClick={onConfirm}
> >
{confirmationBtnLbl} {confirmationButtonLabel}
</LoadingButton> </LoadingButton>
</Stack> </Stack>
</Stack> </GenericDialog>
</Modal>
); );
}; };
Dialog.propTypes = { Dialog.propTypes = {
modelTitle: PropTypes.string.isRequired, title: PropTypes.string.isRequired,
modelDescription: PropTypes.string.isRequired, description: PropTypes.string,
open: PropTypes.bool.isRequired, open: PropTypes.bool.isRequired,
onClose: PropTypes.func.isRequired, onClose: PropTypes.func.isRequired,
title: PropTypes.string.isRequired,
confirmationBtnLbl: PropTypes.string.isRequired,
confirmationBtnOnClick: PropTypes.func.isRequired,
cancelBtnLbl: PropTypes.string.isRequired,
cancelBtnOnClick: PropTypes.func.isRequired,
theme: PropTypes.object.isRequired, theme: PropTypes.object.isRequired,
onCancel: PropTypes.func.isRequired,
confirmationButtonLabel: PropTypes.string.isRequired,
onConfirm: PropTypes.func.isRequired,
isLoading: PropTypes.bool.isRequired, isLoading: PropTypes.bool.isRequired,
description: PropTypes.string,
}; };
export default Dialog; export default Dialog;
@@ -1,7 +1,7 @@
import { useTheme } from "@emotion/react"; import { useTheme } from "@emotion/react";
import { useRef, useState } from "react"; import { useRef, useState } from "react";
import TabPanel from "@mui/lab/TabPanel"; import TabPanel from "@mui/lab/TabPanel";
import { Box, Button, Divider, Modal, Stack, Typography } from "@mui/material"; import { Box, Button, Divider, Stack, Typography } from "@mui/material";
import Avatar from "../../Avatar"; import Avatar from "../../Avatar";
import Field from "../../Inputs/Field"; import Field from "../../Inputs/Field";
import ImageField from "../../Inputs/Image"; import ImageField from "../../Inputs/Image";
@@ -15,6 +15,8 @@ import { clearUptimeMonitorState } from "../../../Features/UptimeMonitors/uptime
import { createToast } from "../../../Utils/toastUtils"; import { createToast } from "../../../Utils/toastUtils";
import { logger } from "../../../Utils/Logger"; import { logger } from "../../../Utils/Logger";
import LoadingButton from "@mui/lab/LoadingButton"; import LoadingButton from "@mui/lab/LoadingButton";
import { GenericDialog } from "../../Dialog/genericDialog";
import Dialog from "../../Dialog";
/** /**
* ProfilePanel component displays a form for editing user profile information * ProfilePanel component displays a form for editing user profile information
@@ -369,101 +371,26 @@ const ProfilePanel = () => {
</Box> </Box>
)} )}
{/* TODO - Update ModalPopup Component with @mui for reusability */} {/* TODO - Update ModalPopup Component with @mui for reusability */}
<Modal
aria-labelledby="modal-delete-account" <Dialog
aria-describedby="delete-account-confirmation"
open={isModalOpen("delete")} open={isModalOpen("delete")}
onClose={() => setIsOpen("")} theme={theme}
disablePortal title={"Really delete this account?"}
> description={
<Stack "If you delete your account, you will no longer be able to sign in, and all of your data will be deleted. Deleting your account is permanent and non-recoverable action."
gap={theme.spacing(5)} }
sx={{ onCancel={() => setIsOpen("")}
position: "absolute", confirmationButtonLabel={"Delete account"}
top: "50%", onConfirm={handleDeleteAccount}
left: "50%", isLoading={isLoading}
transform: "translate(-50%, -50%)", />
width: 500,
bgcolor: theme.palette.background.main, <GenericDialog
border: 1, title={"Upload Image"}
borderColor: theme.palette.border.light,
borderRadius: theme.shape.borderRadius,
boxShadow: 24,
p: theme.spacing(15),
"&:focus": {
outline: "none",
},
}}
>
<Typography
id="modal-delete-account"
component="h1"
>
Really delete this account?
</Typography>
<Typography
id="delete-account-confirmation"
component="p"
>
If you delete your account, you will no longer be able to sign in, and all of
your data will be deleted. Deleting your account is permanent and
non-recoverable action.
</Typography>
<Stack
direction="row"
gap={theme.spacing(5)}
mt={theme.spacing(5)}
justifyContent="flex-end"
>
<Button
variant="text"
color="info"
onClick={() => setIsOpen("")}
>
Cancel
</Button>
<LoadingButton
variant="contained"
color="error"
onClick={handleDeleteAccount}
loading={isLoading}
>
Delete account
</LoadingButton>
</Stack>
</Stack>
</Modal>
<Modal
aria-labelledby="modal-update-picture"
aria-describedby="update-profile-picture"
open={isModalOpen("picture")} open={isModalOpen("picture")}
onClose={closePictureModal} onClose={closePictureModal}
theme={theme}
> >
<Stack
sx={{
position: "absolute",
top: "50%",
left: "50%",
transform: "translate(-50%, -50%)",
width: 475,
bgcolor: theme.palette.background.main,
border: 1,
borderColor: theme.palette.border.light,
borderRadius: theme.shape.borderRadius,
boxShadow: theme.shape.boxShadow,
p: theme.spacing(15),
"&:focus": {
outline: "none",
},
}}
>
<Typography
id="modal-update-picture"
component="h1"
color={theme.palette.text.secondary}
>
Upload Image
</Typography>
<ImageField <ImageField
id="update-profile-picture" id="update-profile-picture"
src={ src={
@@ -519,8 +446,7 @@ const ProfilePanel = () => {
Update Update
</Button> </Button>
</Stack> </Stack>
</Stack> </GenericDialog>
</Modal>
</TabPanel> </TabPanel>
); );
}; };
@@ -1,6 +1,6 @@
import { useTheme } from "@emotion/react"; import { useTheme } from "@emotion/react";
import TabPanel from "@mui/lab/TabPanel"; import TabPanel from "@mui/lab/TabPanel";
import { Box, Button, ButtonGroup, Modal, Stack, Typography } from "@mui/material"; import { Button, ButtonGroup, Stack, Typography } from "@mui/material";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import Field from "../../Inputs/Field"; import Field from "../../Inputs/Field";
import { credentials } from "../../../Validation/validation"; import { credentials } from "../../../Validation/validation";
@@ -10,6 +10,7 @@ import { useSelector } from "react-redux";
import BasicTable from "../../BasicTable"; import BasicTable from "../../BasicTable";
import Select from "../../Inputs/Select"; import Select from "../../Inputs/Select";
import LoadingButton from "@mui/lab/LoadingButton"; import LoadingButton from "@mui/lab/LoadingButton";
import { GenericDialog } from "../../Dialog/genericDialog";
/** /**
* TeamPanel component manages the organization and team members, * TeamPanel component manages the organization and team members,
@@ -31,10 +32,10 @@ const TeamPanel = () => {
const { authToken, user } = useSelector((state) => state.auth); const { authToken, user } = useSelector((state) => state.auth);
//TODO //TODO
const [orgStates, setOrgStates] = useState({ // const [orgStates, setOrgStates] = useState({
name: "Bluewave Labs", // name: "Bluewave Labs",
isEdit: false, // isEdit: false,
}); // });
const [toInvite, setToInvite] = useState({ const [toInvite, setToInvite] = useState({
email: "", email: "",
role: ["0"], role: ["0"],
@@ -134,10 +135,10 @@ const TeamPanel = () => {
}, [errors, toInvite.email]); }, [errors, toInvite.email]);
// RENAME ORGANIZATION // RENAME ORGANIZATION
const toggleEdit = () => { // const toggleEdit = () => {
setOrgStates((prev) => ({ ...prev, isEdit: !prev.isEdit })); // setOrgStates((prev) => ({ ...prev, isEdit: !prev.isEdit }));
}; // };
const handleRename = () => {}; // const handleRename = () => {};
// INVITE MEMBER // INVITE MEMBER
const [isOpen, setIsOpen] = useState(false); const [isOpen, setIsOpen] = useState(false);
@@ -327,50 +328,16 @@ const TeamPanel = () => {
table={"team"} table={"team"}
/> />
</Stack> </Stack>
<Modal
aria-labelledby="modal-invite-member" <GenericDialog
aria-describedby="invite-member-to-team" title={"Invite new team member"}
description={
"When you add a new team member, they will get access to all monitors."
}
open={isOpen} open={isOpen}
onClose={closeInviteModal} onClose={closeInviteModal}
theme={theme}
> >
<Stack
gap={theme.spacing(5)}
sx={{
position: "absolute",
top: "50%",
left: "50%",
transform: "translate(-50%, -50%)",
width: 450,
bgcolor: theme.palette.background.main,
border: 1,
borderColor: theme.palette.border.light,
borderRadius: theme.shape.borderRadius,
boxShadow: theme.shape.boxShadow,
p: theme.spacing(15),
"&:focus": {
outline: "none",
},
}}
>
<Box>
<Typography
id="modal-invite-member"
component="h1"
fontWeight={600}
fontColor={theme.palette.text.secondary}
>
Invite new team member
</Typography>
<Typography
id="invite-member-to-team"
component="p"
fontSize={13}
color={theme.palette.text.accent}
sx={{ mt: theme.spacing(1), mb: theme.spacing(4) }}
>
When you add a new team member, they will get access to all monitors.
</Typography>
</Box>
<Field <Field
type="email" type="email"
id="input-team-member" id="input-team-member"
@@ -419,8 +386,7 @@ const TeamPanel = () => {
Send invite Send invite
</LoadingButton> </LoadingButton>
</Stack> </Stack>
</Stack> </GenericDialog>
</Modal>
</TabPanel> </TabPanel>
); );
}; };
+9 -32
View File
@@ -12,11 +12,10 @@ import { useNavigate } from "react-router";
import { getAppSettings, updateAppSettings } from "../../Features/Settings/settingsSlice"; import { getAppSettings, updateAppSettings } from "../../Features/Settings/settingsSlice";
import { useState, useEffect } from "react"; import { useState, useEffect } from "react";
import Select from "../../Components/Inputs/Select"; import Select from "../../Components/Inputs/Select";
import { advancedSettingsValidation } from "../../Validation/validation";
import { buildErrors, hasValidationErrors } from "../../Validation/error";
const AdvancedSettings = ({ isAdmin }) => { const AdvancedSettings = ({ isAdmin }) => {
const navigate = useNavigate(); const navigate = useNavigate();
useEffect(() => { useEffect(() => {
if (!isAdmin) { if (!isAdmin) {
navigate("/"); navigate("/");
@@ -40,12 +39,11 @@ const AdvancedSettings = ({ isAdmin }) => {
redisPort: "", redisPort: "",
pagespeedApiKey: "", pagespeedApiKey: "",
}); });
const [errors, setErrors] = useState({});
useEffect(() => { useEffect(() => {
const getSettings = async () => { const getSettings = async () => {
const action = await dispatch(getAppSettings({ authToken })); const action = await dispatch(getAppSettings({ authToken }));
if (action.payload?.success) { if (action.payload.success) {
setLocalSettings(action.payload.data); setLocalSettings(action.payload.data);
} else { } else {
createToast({ body: "Failed to get settings" }); createToast({ body: "Failed to get settings" });
@@ -77,20 +75,9 @@ const AdvancedSettings = ({ isAdmin }) => {
const handleChange = (event) => { const handleChange = (event) => {
const { value, id } = event.target; const { value, id } = event.target;
setLocalSettings({ ...localSettings, [id]: value }); setLocalSettings({ ...localSettings, [id]: value });
const { error } = advancedSettingsValidation.validate(
{ [id]: value },
{
abortEarly: false,
}
);
setErrors((prev) => {
return buildErrors(prev, id, error);
});
}; };
const handleSave = async () => { const handleSave = async () => {
if (hasValidationErrors(localSettings, advancedSettingsValidation, setErrors))
return;
const action = await dispatch( const action = await dispatch(
updateAppSettings({ settings: localSettings, authToken }) updateAppSettings({ settings: localSettings, authToken })
); );
@@ -131,7 +118,6 @@ const AdvancedSettings = ({ isAdmin }) => {
label="API URL Host" label="API URL Host"
value={localSettings.apiBaseUrl} value={localSettings.apiBaseUrl}
onChange={handleChange} onChange={handleChange}
error={errors.apiBaseUrl}
/> />
<Select <Select
id="logLevel" id="logLevel"
@@ -140,7 +126,6 @@ const AdvancedSettings = ({ isAdmin }) => {
items={logItems} items={logItems}
value={logItemLookup[localSettings.logLevel]} value={logItemLookup[localSettings.logLevel]}
onChange={handleLogLevel} onChange={handleLogLevel}
error={errors.logLevel}
/> />
</Stack> </Stack>
</ConfigBox> </ConfigBox>
@@ -148,8 +133,8 @@ const AdvancedSettings = ({ isAdmin }) => {
<Box> <Box>
<Typography component="h1">Email settings</Typography> <Typography component="h1">Email settings</Typography>
<Typography sx={{ mt: theme.spacing(2) }}> <Typography sx={{ mt: theme.spacing(2) }}>
Set your host email settings here. These settings are used for Set your host email settings here. These settings are used for sending
sending system emails. system emails.
</Typography> </Typography>
</Box> </Box>
<Stack gap={theme.spacing(20)}> <Stack gap={theme.spacing(20)}>
@@ -160,7 +145,6 @@ const AdvancedSettings = ({ isAdmin }) => {
name="systemEmailHost" name="systemEmailHost"
value={localSettings.systemEmailHost} value={localSettings.systemEmailHost}
onChange={handleChange} onChange={handleChange}
error={errors.systemEmailHost}
/> />
<Field <Field
type="number" type="number"
@@ -169,7 +153,6 @@ const AdvancedSettings = ({ isAdmin }) => {
name="systemEmailPort" name="systemEmailPort"
value={localSettings.systemEmailPort.toString()} value={localSettings.systemEmailPort.toString()}
onChange={handleChange} onChange={handleChange}
error={errors.systemEmailPort}
/> />
<Field <Field
type="email" type="email"
@@ -178,7 +161,6 @@ const AdvancedSettings = ({ isAdmin }) => {
name="systemEmailAddress" name="systemEmailAddress"
value={localSettings.systemEmailAddress} value={localSettings.systemEmailAddress}
onChange={handleChange} onChange={handleChange}
error={errors.systemEmailAddress}
/> />
<Field <Field
type="text" type="text"
@@ -187,7 +169,6 @@ const AdvancedSettings = ({ isAdmin }) => {
name="systemEmailPassword" name="systemEmailPassword"
value={localSettings.systemEmailPassword} value={localSettings.systemEmailPassword}
onChange={handleChange} onChange={handleChange}
error={errors.systemEmailPassword}
/> />
</Stack> </Stack>
</ConfigBox> </ConfigBox>
@@ -206,7 +187,6 @@ const AdvancedSettings = ({ isAdmin }) => {
name="jwtTTL" name="jwtTTL"
value={localSettings.jwtTTL} value={localSettings.jwtTTL}
onChange={handleChange} onChange={handleChange}
error={errors.jwtTTL}
/> />
<Field <Field
type="text" type="text"
@@ -215,7 +195,6 @@ const AdvancedSettings = ({ isAdmin }) => {
name="dbType" name="dbType"
value={localSettings.dbType} value={localSettings.dbType}
onChange={handleChange} onChange={handleChange}
error={errors.dbType}
/> />
<Field <Field
type="text" type="text"
@@ -224,7 +203,6 @@ const AdvancedSettings = ({ isAdmin }) => {
name="redisHost" name="redisHost"
value={localSettings.redisHost} value={localSettings.redisHost}
onChange={handleChange} onChange={handleChange}
error={errors.redisHost}
/> />
<Field <Field
type="number" type="number"
@@ -233,7 +211,6 @@ const AdvancedSettings = ({ isAdmin }) => {
name="redisPort" name="redisPort"
value={localSettings.redisPort.toString()} value={localSettings.redisPort.toString()}
onChange={handleChange} onChange={handleChange}
error={errors.redisPort}
/> />
<Field <Field
type="text" type="text"
@@ -242,7 +219,6 @@ const AdvancedSettings = ({ isAdmin }) => {
name="pagespeedApiKey" name="pagespeedApiKey"
value={localSettings.pagespeedApiKey} value={localSettings.pagespeedApiKey}
onChange={handleChange} onChange={handleChange}
error={errors.pagespeedApiKey}
/> />
</Stack> </Stack>
</ConfigBox> </ConfigBox>
@@ -252,9 +228,7 @@ const AdvancedSettings = ({ isAdmin }) => {
</Box> </Box>
<Box> <Box>
<Typography component="h2">BlueWave Uptime v1.0.0</Typography> <Typography component="h2">BlueWave Uptime v1.0.0</Typography>
<Typography <Typography sx={{ mt: theme.spacing(2), mb: theme.spacing(6), opacity: 0.6 }}>
sx={{ mt: theme.spacing(2), mb: theme.spacing(6), opacity: 0.6 }}
>
Developed by Bluewave Labs. Developed by Bluewave Labs.
</Typography> </Typography>
<Link <Link
@@ -264,7 +238,10 @@ const AdvancedSettings = ({ isAdmin }) => {
/> />
</Box> </Box>
</ConfigBox> </ConfigBox>
<Stack direction="row" justifyContent="flex-end"> <Stack
direction="row"
justifyContent="flex-end"
>
<LoadingButton <LoadingButton
loading={settings.isLoading || settings.authIsLoading} loading={settings.isLoading || settings.authIsLoading}
variant="contained" variant="contained"
@@ -28,7 +28,6 @@ import {
MS_PER_WEEK, MS_PER_WEEK,
} from "../../../Utils/timeUtils"; } from "../../../Utils/timeUtils";
import { useNavigate, useParams } from "react-router-dom"; import { useNavigate, useParams } from "react-router-dom";
import { buildErrors, hasValidationErrors } from "../../../Validation/error";
const getDurationAndUnit = (durationInMs) => { const getDurationAndUnit = (durationInMs) => {
if (durationInMs % MS_PER_DAY === 0) { if (durationInMs % MS_PER_DAY === 0) {
@@ -177,6 +176,16 @@ const CreateMaintenance = () => {
fetchMonitors(); fetchMonitors();
}, [authToken, user]); }, [authToken, user]);
const buildErrors = (prev, id, error) => {
const updatedErrors = { ...prev };
if (error) {
updatedErrors[id] = error.details[0].message;
} else {
delete updatedErrors[id];
}
return updatedErrors;
};
const handleSearch = (value) => { const handleSearch = (value) => {
setSearch(value); setSearch(value);
}; };
@@ -215,8 +224,20 @@ const CreateMaintenance = () => {
}; };
const handleSubmit = async () => { const handleSubmit = async () => {
if(hasValidationErrors(form, maintenanceWindowValidation, setErrors)) const { error } = maintenanceWindowValidation.validate(form, {
abortEarly: false,
});
// If errors, return early
if (error) {
const newErrors = {};
error.details.forEach((err) => {
newErrors[err.path[0]] = err.message;
});
setErrors(newErrors);
logger.error(error);
return; return;
}
// Build timestamp for maintenance window from startDate and startTime // Build timestamp for maintenance window from startDate and startTime
const start = dayjs(form.startDate) const start = dayjs(form.startDate)
.set("hour", form.startTime.hour()) .set("hour", form.startTime.hour())
@@ -2,23 +2,16 @@ import { useState } from "react";
import { useTheme } from "@emotion/react"; import { useTheme } from "@emotion/react";
import { useNavigate } from "react-router-dom"; import { useNavigate } from "react-router-dom";
import { useSelector } from "react-redux"; import { useSelector } from "react-redux";
import { import { IconButton, Menu, MenuItem } from "@mui/material";
Button,
IconButton,
Menu,
MenuItem,
Modal,
Stack,
Typography,
} from "@mui/material";
import LoadingButton from "@mui/lab/LoadingButton";
import { logger } from "../../../../Utils/Logger"; import { logger } from "../../../../Utils/Logger";
import Settings from "../../../../assets/icons/settings-bold.svg?react"; import Settings from "../../../../assets/icons/settings-bold.svg?react";
import PropTypes from "prop-types"; import PropTypes from "prop-types";
import { networkService } from "../../../../main"; import { networkService } from "../../../../main";
import { createToast } from "../../../../Utils/toastUtils"; import { createToast } from "../../../../Utils/toastUtils";
const ActionsMenu = ({ isAdmin, maintenanceWindow, updateCallback }) => { import Dialog from "../../../../Components/Dialog";
const ActionsMenu = ({ /* isAdmin, */ maintenanceWindow, updateCallback }) => {
maintenanceWindow; maintenanceWindow;
const { authToken } = useSelector((state) => state.auth); const { authToken } = useSelector((state) => state.auth);
const [anchorEl, setAnchorEl] = useState(null); const [anchorEl, setAnchorEl] = useState(null);
@@ -155,71 +148,21 @@ const ActionsMenu = ({ isAdmin, maintenanceWindow, updateCallback }) => {
Remove Remove
</MenuItem> </MenuItem>
</Menu> </Menu>
<Modal <Dialog
aria-labelledby="modal-delete-monitor"
aria-describedby="delete-monitor-confirmation"
open={isOpen} open={isOpen}
onClose={(e) => { theme={theme}
title={"Do you really want to remove this maintenance window?"}
onCancel={(e) => {
e.stopPropagation(); e.stopPropagation();
setIsOpen(false); setIsOpen(false);
}} }}
> confirmationButtonLabel={"Delete"}
<Stack onConfirm={(e) => {
gap={theme.spacing(2)}
sx={{
position: "absolute",
top: "50%",
left: "50%",
transform: "translate(-50%, -50%)",
width: 400,
bgcolor: theme.palette.background.main,
border: 1,
borderColor: theme.palette.border.light,
borderRadius: theme.shape.borderRadius,
boxShadow: 24,
p: theme.spacing(15),
"&:focus": {
outline: "none",
},
}}
>
<Typography
id="modal-delete-maintenance"
component="h2"
variant="h2"
>
Do you really want to remove this maintenance window?
</Typography>
<Stack
direction="row"
gap={theme.spacing(4)}
mt={theme.spacing(12)}
justifyContent="flex-end"
>
<Button
variant="text"
color="info"
onClick={(e) => {
e.stopPropagation();
setIsOpen(false);
}}
>
Cancel
</Button>
<LoadingButton
loading={isLoading}
variant="contained"
color="error"
onClick={(e) => {
e.stopPropagation(e); e.stopPropagation(e);
handleRemove(e); handleRemove(e);
}} }}
> isLoading={isLoading}
Delete />
</LoadingButton>
</Stack>
</Stack>
</Modal>
</> </>
); );
}; };
+7 -10
View File
@@ -453,20 +453,17 @@ const Configure = () => {
</Stack> </Stack>
</> </>
)} )}
<Dialog <Dialog
modelTitle="modal-delete-monitor"
modelDescription="delete-monitor-confirmation"
open={isOpen} open={isOpen}
onClose={() => setIsOpen(false)}
title="Do you really want to delete this monitor?"
confirmationBtnLbl="Delete"
confirmationBtnOnClick={handleRemove}
cancelBtnLbl="Cancel"
cancelBtnOnClick={() => setIsOpen(false)}
theme={theme} theme={theme}
isLoading={isLoading} title="Do you really want to delete this monitor?"
description="Once deleted, this monitor cannot be retrieved." description="Once deleted, this monitor cannot be retrieved."
></Dialog> onCancel={() => setIsOpen(false)}
confirmationButtonLabel="Delete"
onConfirm={handleRemove}
isLoading={isLoading}
/>
</Stack> </Stack>
); );
}; };
+13 -13
View File
@@ -188,25 +188,25 @@ const ActionsMenu = ({ monitor, isAdmin, updateCallback }) => {
)} )}
</Menu> </Menu>
<Dialog <Dialog
modelTitle="modal-delete-monitor"
modelDescription="delete-monitor-confirmation"
open={isOpen} open={isOpen}
onClose={() => setIsOpen(false)} theme={theme}
title="Do you really want to delete this monitor?" title="Do you really want to delete this monitor?"
confirmationBtnLbl="Delete" description="Once deleted, this monitor cannot be retrieved."
confirmationBtnOnClick={(e) => { /* Do we need stop propagation? */
e.stopPropagation(); onCancel={(e) => {
handleRemove(e);
}}
cancelBtnLbl="Cancel"
cancelBtnOnClick={(e) => {
e.stopPropagation(); e.stopPropagation();
setIsOpen(false); setIsOpen(false);
}} }}
theme={theme} confirmationButtonLabel="Delete"
/* Do we need stop propagation? */
onConfirm={(e) => {
e.stopPropagation();
handleRemove(e);
}}
isLoading={isLoading} isLoading={isLoading}
description="Once deleted, this monitor cannot be retrieved." modelTitle="modal-delete-monitor"
></Dialog> modelDescription="delete-monitor-confirmation"
/>
</> </>
); );
}; };
+14 -63
View File
@@ -1,6 +1,6 @@
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { useTheme } from "@emotion/react"; import { useTheme } from "@emotion/react";
import { Box, Button, Modal, Stack, Tooltip, Typography } from "@mui/material"; import { Box, Stack, Tooltip, Typography } from "@mui/material";
import { useDispatch, useSelector } from "react-redux"; import { useDispatch, useSelector } from "react-redux";
import { useNavigate, useParams } from "react-router"; import { useNavigate, useParams } from "react-router";
import { import {
@@ -25,6 +25,7 @@ import PlayCircleOutlineRoundedIcon from "@mui/icons-material/PlayCircleOutlineR
import SkeletonLayout from "./skeleton"; import SkeletonLayout from "./skeleton";
import useUtils from "../../Monitors/utils"; import useUtils from "../../Monitors/utils";
import "./index.css"; import "./index.css";
import Dialog from "../../../Components/Dialog";
const PageSpeedConfigure = () => { const PageSpeedConfigure = () => {
const theme = useTheme(); const theme = useTheme();
@@ -37,6 +38,7 @@ const PageSpeedConfigure = () => {
const [monitor, setMonitor] = useState({}); const [monitor, setMonitor] = useState({});
const [errors, setErrors] = useState({}); const [errors, setErrors] = useState({});
const { statusColor, pagespeedStatusMsg, determineState } = useUtils(); const { statusColor, pagespeedStatusMsg, determineState } = useUtils();
const [buttonLoading, setButtonLoading] = useState(false);
const idMap = { const idMap = {
"monitor-url": "url", "monitor-url": "url",
"monitor-name": "name", "monitor-name": "name",
@@ -156,12 +158,14 @@ const PageSpeedConfigure = () => {
const [isOpen, setIsOpen] = useState(false); const [isOpen, setIsOpen] = useState(false);
const handleRemove = async (event) => { const handleRemove = async (event) => {
event.preventDefault(); event.preventDefault();
setButtonLoading(true);
const action = await dispatch(deletePageSpeed({ authToken, monitor })); const action = await dispatch(deletePageSpeed({ authToken, monitor }));
if (action.meta.requestStatus === "fulfilled") { if (action.meta.requestStatus === "fulfilled") {
navigate("/pagespeed"); navigate("/pagespeed");
} else { } else {
createToast({ body: "Failed to delete monitor." }); createToast({ body: "Failed to delete monitor." });
} }
setButtonLoading(false);
}; };
return ( return (
@@ -428,69 +432,16 @@ const PageSpeedConfigure = () => {
</Stack> </Stack>
</> </>
)} )}
<Modal <Dialog
aria-labelledby="modal-delete-pagespeed-monitor"
aria-describedby="delete-pagespeed-monitor-confirmation"
open={isOpen} open={isOpen}
onClose={() => setIsOpen(false)} theme={theme}
disablePortal title={"Do you really want to delete this monitor?"}
> description={"Once deleted, this monitor cannot be retrieved."}
<Stack onCancel={() => setIsOpen(false)}
gap={theme.spacing(2)} confirmationButtonLabel={"Delete"}
sx={{ onConfirm={handleRemove}
position: "absolute", isLoading={buttonLoading}
top: "50%", />
left: "50%",
transform: "translate(-50%, -50%)",
width: 400,
bgcolor: theme.palette.background.main,
border: 1,
borderColor: theme.palette.border.light,
borderRadius: theme.shape.borderRadius,
boxShadow: 24,
p: theme.spacing(15),
"&:focus": {
outline: "none",
},
}}
>
<Typography
id="modal-delete-pagespeed-monitor"
component="h2"
variant="h2"
fontWeight={500}
>
Do you really want to delete this monitor?
</Typography>
<Typography
id="delete-pagespeed-monitor-confirmation"
variant="body1"
>
Once deleted, this monitor cannot be retrieved.
</Typography>
<Stack
direction="row"
gap={theme.spacing(4)}
mt={theme.spacing(12)}
justifyContent="flex-end"
>
<Button
variant="text"
color="info"
onClick={() => setIsOpen(false)}
>
Cancel
</Button>
<Button
variant="contained"
color="error"
onClick={handleRemove}
>
Delete
</Button>
</Stack>
</Stack>
</Modal>
</Stack> </Stack>
); );
}; };
+11 -18
View File
@@ -263,18 +263,15 @@ const Settings = ({ isAdmin }) => {
</Box> </Box>
</Stack> </Stack>
<Dialog <Dialog
modelTitle="model-clear-stats"
modelDescription="clear-stats-confirmation"
open={isOpen.deleteStats} open={isOpen.deleteStats}
onClose={() => setIsOpen(deleteStatsMonitorsInitState)}
title="Do you want to clear all stats?"
confirmationBtnLbl="Yes, clear all stats"
confirmationBtnOnClick={handleClearStats}
cancelBtnLbl="Cancel"
cancelBtnOnClick={() => setIsOpen(deleteStatsMonitorsInitState)}
theme={theme} theme={theme}
title="Do you want to clear all stats?"
description="Once deleted, this monitor cannot be retrieved."
onCancel={() => setIsOpen(deleteStatsMonitorsInitState)}
confirmationButtonLabel="Yes, clear all stats"
onConfirm={handleClearStats}
isLoading={isLoading || authIsLoading || checksIsLoading} isLoading={isLoading || authIsLoading || checksIsLoading}
></Dialog> />
</ConfigBox> </ConfigBox>
)} )}
{isAdmin && ( {isAdmin && (
@@ -314,18 +311,14 @@ const Settings = ({ isAdmin }) => {
</Box> </Box>
</Stack> </Stack>
<Dialog <Dialog
modelTitle="model-delete-all-monitors"
modelDescription="delete-all-monitors-confirmation"
open={isOpen.deleteMonitors} open={isOpen.deleteMonitors}
onClose={() => setIsOpen(deleteStatsMonitorsInitState)}
title="Do you want to remove all monitors?"
confirmationBtnLbl="Yes, clear all monitors"
confirmationBtnOnClick={handleDeleteAllMonitors}
cancelBtnLbl="Cancel"
cancelBtnOnClick={() => setIsOpen(deleteStatsMonitorsInitState)}
theme={theme} theme={theme}
title="Do you want to remove all monitors?"
onCancel={() => setIsOpen(deleteStatsMonitorsInitState)}
confirmationButtonLabel="Yes, clear all monitors"
onConfirm={handleDeleteAllMonitors}
isLoading={isLoading || authIsLoading || checksIsLoading} isLoading={isLoading || authIsLoading || checksIsLoading}
></Dialog> />
</ConfigBox> </ConfigBox>
)} )}
{isAdmin && ( {isAdmin && (
-25
View File
@@ -1,25 +0,0 @@
const buildErrors = (prev, id, error) => {
const updatedErrors = { ...prev };
if (error) {
updatedErrors[id] = error.details[0].message?? "Validation error";
} else {
delete updatedErrors[id];
}
return updatedErrors;
};
const hasValidationErrors = (form, validation, setErrors) => {
const { error } = validation.validate(form, {
abortEarly: false,
});
if (error) {
const newErrors = {};
error.details.forEach((err) => {
newErrors[err.path[0]] = err.message?? "Validation error";
});
setErrors(newErrors);
return true;
}
return false;
};
export { buildErrors, hasValidationErrors };
-33
View File
@@ -128,43 +128,10 @@ const maintenanceWindowValidation = joi.object({
monitors: joi.array().min(1), monitors: joi.array().min(1),
}); });
const advancedSettingsValidation = joi.object({
apiBaseUrl: joi.string().uri({ allowRelative: true }).trim().messages({
"string.empty": "API base url is required.",
"string.uri": "The URL you provided is not valid.",
}),
logLevel: joi.string().valid("debug", "none", "error", "warn").allow(""),
systemEmailHost: joi.string().allow(''),
systemEmailPort: joi.string().allow(''),
systemEmailAddress: joi
.string().allow(''),
systemEmailPassword: joi.string().allow(''),
jwtTTL: joi
.string()
.trim()
.messages({
"string.empty": "JWT TTL is required."
}),
dbType: joi.string().trim().messages({
"string.empty": "DB type is required",
}),
redisHost: joi.string().trim().messages({
"string.empty": "Redis host is required",
}),
redisPort: joi.string().allow('').custom((value, helpers) => {
if(value && isNaN(parseInt(value))){
return helpers.message("Redit port must be a number")
}
return value
}),
pagespeedApiKey: joi.string().allow('')
});
export { export {
credentials, credentials,
imageValidation, imageValidation,
monitorValidation, monitorValidation,
settingsValidation, settingsValidation,
maintenanceWindowValidation, maintenanceWindowValidation,
advancedSettingsValidation,
}; };
+60
View File
@@ -173,6 +173,65 @@ const loginUser = async (req, res, next) => {
} }
}; };
/**
* Generates new auth token if the refresh token is valid
* @async
* @param {Express.Request} req - The Express request object.
* @property {Object} req.headers - The parameter of the request.
* @param {Express.Response} res - The Express response object.
* @param {function} next - The next middleware function.
* @returns {Object} The response object with a success status, a message indicating new auth token is generated.
* @throws {Error} If there is an error during the process such as any of the token is not received
*/
const refreshAuthToken = async (req, res, next) => {
try {
// check for refreshToken
const refreshToken = req.headers["x-refresh-token"];
if (!refreshToken) {
// No refresh token provided
const error = new Error(errorMessages.NO_REFRESH_TOKEN);
error.status = 401;
error.service = SERVICE_NAME;
error.method = "refreshAuthToken";
return next(error);
}
// Verify refresh token
const appSettings = await req.settingsService.getSettings();
const { refreshTokenSecret } = appSettings;
jwt.verify(refreshToken, refreshTokenSecret, async (refreshErr, refreshDecoded) => {
if (refreshErr) {
// Invalid or expired refresh token, trigger logout
const errorMessage =
refreshErr.name === "TokenExpiredError"
? errorMessages.EXPIRED_REFRESH_TOKEN
: errorMessages.INVALID_REFRESH_TOKEN;
const error = new Error(errorMessage);
error.status = 401;
error.service = SERVICE_NAME;
return next(error);
}
});
// Refresh token is valid and unexpired, generate new access token
const oldAuthToken = getTokenFromHeaders(req.headers);
const { jwtSecret } = await req.settingsService.getSettings();
const payloadData = jwt.verify(oldAuthToken, jwtSecret, { ignoreExpiration: true });
// delete old token related data
delete payloadData.iat;
delete payloadData.exp;
const newAuthToken = issueToken(payloadData, tokenType.ACCESS_TOKEN, appSettings);
return res.status(200).json({
success: true,
msg: successMessages.AUTH_TOKEN_REFRESHED,
data: { user: payloadData, token: newAuthToken, refreshToken: refreshToken },
});
} catch (error) {
next(handleError(error, SERVICE_NAME, "refreshAuthToken"));
}
};
/** /**
* Edits a user's information. If the user wants to change their password, the current password is checked before updating to the new password. * 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 * @async
@@ -455,6 +514,7 @@ export {
issueToken, issueToken,
registerUser, registerUser,
loginUser, loginUser,
refreshAuthToken,
editUser, editUser,
checkSuperadminExists, checkSuperadminExists,
requestRecovery, requestRecovery,
+71
View File
@@ -261,6 +261,77 @@
} }
} }
}, },
"/auth/refresh": {
"post": {
"tags": [
"auth"
],
"description": "Generates a new auth token if the refresh token is valid.",
"requestBody": {
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {}
}
}
},
"required": false
},
"parameters": [
{
"name": "x-refresh-token",
"in": "header",
"description": "Refresh token required to generate a new auth token.",
"required": true,
"schema": {
"type": "string"
}
},
{
"name": "authorization",
"in": "header",
"description": "Old access token, used to extract payload).",
"required": true,
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "New access token generated.",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/SuccessResponse"
}
}
}
},
"401": {
"description": "Unauthorized or invalid refresh token.",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorResponse"
}
}
}
},
"500": {
"description": "Internal Server Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorResponse"
}
}
}
}
}
}
},
"/auth/user/{userId}": { "/auth/user/{userId}": {
"put": { "put": {
"tags": [ "tags": [
+461 -378
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -29,7 +29,7 @@
"multer": "1.4.5-lts.1", "multer": "1.4.5-lts.1",
"nodemailer": "^6.9.14", "nodemailer": "^6.9.14",
"ping": "0.4.4", "ping": "0.4.4",
"sharp": "0.33.4", "sharp": "0.33.5",
"ssl-checker": "2.0.10", "ssl-checker": "2.0.10",
"swagger-ui-express": "5.0.1", "swagger-ui-express": "5.0.1",
"winston": "^3.13.0" "winston": "^3.13.0"
+2
View File
@@ -11,6 +11,7 @@ const upload = multer();
import { import {
registerUser, registerUser,
loginUser, loginUser,
refreshAuthToken,
editUser, editUser,
requestRecovery, requestRecovery,
validateRecovery, validateRecovery,
@@ -23,6 +24,7 @@ import {
//Auth routes //Auth routes
router.post("/register", upload.single("profileImage"), registerUser); router.post("/register", upload.single("profileImage"), registerUser);
router.post("/login", loginUser); router.post("/login", loginUser);
router.post("/refresh", refreshAuthToken);
router.put("/user/:userId", upload.single("profileImage"), verifyJWT, editUser); router.put("/user/:userId", upload.single("profileImage"), verifyJWT, editUser);
router.get("/users/superadmin", checkSuperadminExists); router.get("/users/superadmin", checkSuperadminExists);
router.get("/users", verifyJWT, isAllowed(["admin", "superadmin"]), getAllUsers); router.get("/users", verifyJWT, isAllowed(["admin", "superadmin"]), getAllUsers);
@@ -2,6 +2,7 @@ import {
issueToken, issueToken,
registerUser, registerUser,
loginUser, loginUser,
refreshAuthToken,
editUser, editUser,
checkSuperadminExists, checkSuperadminExists,
requestRecovery, requestRecovery,
@@ -13,8 +14,9 @@ import {
import jwt from "jsonwebtoken"; import jwt from "jsonwebtoken";
import { errorMessages, successMessages } from "../../utils/messages.js"; import { errorMessages, successMessages } from "../../utils/messages.js";
import sinon from "sinon"; import sinon from "sinon";
import { tokenType } from "../../utils/utils.js"; import { getTokenFromHeaders, tokenType } from "../../utils/utils.js";
import logger from "../../utils/logger.js"; import logger from "../../utils/logger.js";
import e from "cors";
describe("Auth Controller - issueToken", () => { describe("Auth Controller - issueToken", () => {
let stub; let stub;
@@ -303,6 +305,97 @@ describe("Auth Controller - loginUser", () => {
}); });
}); });
describe("Auth Controller - refreshAuthToken", () => {
let req, res, next, issueTokenStub;
beforeEach(() => {
req = {
headers: {
"x-refresh-token": "valid_refresh_token",
authorization: "Bearer old_auth_token",
},
settingsService: {
getSettings: sinon.stub().resolves({
jwtSecret: "my_secret",
refreshTokenSecret: "my_refresh_secret",
}),
},
};
res = {
status: sinon.stub().returnsThis(),
json: sinon.stub(),
};
next = sinon.stub();
sinon.stub(jwt, "verify");
issueTokenStub = sinon.stub().returns("new_auth_token");
sinon.replace({ issueToken }, "issueToken", issueTokenStub);
});
afterEach(() => {
sinon.restore();
});
it("should reject if no refresh token is provided", async () => {
delete req.headers["x-refresh-token"];
await refreshAuthToken(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal(errorMessages.NO_REFRESH_TOKEN);
expect(next.firstCall.args[0].status).to.equal(401);
});
it("should reject if the refresh token is invalid", async () => {
jwt.verify.yields(new Error("invalid token"));
await refreshAuthToken(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal(errorMessages.INVALID_REFRESH_TOKEN);
expect(next.firstCall.args[0].status).to.equal(401);
});
it("should reject if the refresh token is expired", async () => {
const error = new Error("Token expired");
error.name = "TokenExpiredError";
jwt.verify.yields(error);
await refreshAuthToken(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal(errorMessages.EXPIRED_REFRESH_TOKEN);
expect(next.firstCall.args[0].status).to.equal(401);
});
it("should reject if settingsService.getSettings fails", async () => {
req.settingsService.getSettings.rejects(
new Error("settingsService.getSettings error")
);
await refreshAuthToken(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("settingsService.getSettings error");
});
it("should generate a new auth token if the refresh token is valid", async () => {
const decodedPayload = { expiresIn: "60" };
jwt.verify.callsFake(() => {
return decodedPayload;
});
await refreshAuthToken(req, res, next);
expect(res.status.calledWith(200)).to.be.true;
expect(
res.json.calledWith({
success: true,
msg: successMessages.AUTH_TOKEN_REFRESHED,
data: {
user: decodedPayload,
token: sinon.match.string,
refreshToken: "valid_refresh_token",
},
})
).to.be.true;
});
});
describe("Auth Controller - editUser", async () => { describe("Auth Controller - editUser", async () => {
let req, res, next, stub, user; let req, res, next, stub, user;
beforeEach(() => { beforeEach(() => {
+1 -1
View File
@@ -62,7 +62,6 @@ const successMessages = {
ALERT_EDIT: "Alert edited successfully", ALERT_EDIT: "Alert edited successfully",
ALERT_DELETE: "Alert deleted successfully", ALERT_DELETE: "Alert deleted successfully",
// Auth Controller
AUTH_CREATE_USER: "User created successfully", AUTH_CREATE_USER: "User created successfully",
AUTH_LOGIN_USER: "User logged in successfully", AUTH_LOGIN_USER: "User logged in successfully",
AUTH_LOGOUT_USER: "User logged out successfully", AUTH_LOGOUT_USER: "User logged out successfully",
@@ -72,6 +71,7 @@ const successMessages = {
AUTH_RESET_PASSWORD: "Password reset successfully", AUTH_RESET_PASSWORD: "Password reset successfully",
AUTH_ADMIN_CHECK: "Admin check completed successfully", AUTH_ADMIN_CHECK: "Admin check completed successfully",
AUTH_DELETE_USER: "User deleted successfully", AUTH_DELETE_USER: "User deleted successfully",
AUTH_TOKEN_REFRESHED: "Auth token is refreshed",
// Check Controller // Check Controller
CHECK_CREATE: "Check created successfully", CHECK_CREATE: "Check created successfully",