Merge branch 'develop' into enhancement/check-if-url-resolves

This commit is contained in:
om-3004 committed 2024-10-16 10:04:41 +05:30
commit 2c85828144
30 files changed
+2036 -274

No files matched your search

+16
View File
@@ -0,0 +1,16 @@
{
"printWidth": 90,
"useTabs": true,
"tabWidth": 2,
"singleQuote": false,
"bracketSpacing": true,
"proseWrap": "preserve",
"bracketSameLine": false,
"singleAttributePerLine": true,
"semi": true,
"jsx-single-quote": false,
"quoteProps": "as-needed",
"arrowParens": "always",
"trailingComma": "es5",
"htmlWhitespaceSensitivity": "css"
}
+69
View File
@@ -0,0 +1,69 @@
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in the **bluewave-uptime** project and community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community, especially during Hacktoberfest, where we encourage new contributors to join and feel supported.
## Our Standards
Examples of behavior that contributes to a positive environment for our community include:
- Demonstrating empathy and kindness toward other people
- Being respectful of differing opinions, viewpoints, and experiences
- Giving and gracefully accepting constructive feedback
- Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
- Focusing on what is best not just for us as individuals, but for the overall community
Examples of unacceptable behavior include:
- The use of sexualized language or imagery, and sexual attention or advances of any kind
- Trolling, insulting or derogatory comments, and personal or political attacks
- Public or private harassment
- Publishing others' private information, such as a physical or email address, without their explicit permission
- Other conduct which could reasonably be considered inappropriate in a professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned with this Code of Conduct, especially during Hacktoberfest to ensure a positive experience for all contributors.
## Scope
This Code of Conduct applies within all project spaces, and it also applies when an individual is officially representing the project or its community in public spaces. Examples of representing our project include using an official project email address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at hello@bluewavelabs.ca. All complaints will be reviewed and investigated promptly and fairly.
All project team members are obligated to respect the privacy and security of the reporter of any incident.
## Enforcement Guidelines
Project maintainers will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from project maintainers, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series of actions.
**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within the community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant](https://www.contributor-covenant.org), version 2.0, available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
---
By following this Code of Conduct, we can ensure a welcoming and inclusive environment, encouraging new contributors to engage with the project and the community. Thank you for helping make **bluewave-uptime** a positive space for all!
+1
View File
@@ -77,6 +77,7 @@ Once it's filed:
This section guides you through submitting an enhancement suggestion for the application, **including completely new features and minor improvements to existing functionality**. Following these guidelines will help maintainers and the community understand your enhancements and find related suggestions.
- Make sure that you are using the latest version.
- Make sure you run the code locally. The Uptime Manager [documentation](https://bluewavelabs.gitbook.io/uptime-manager) covers it.
- Find out if the functionality is already covered, maybe by an individual configuration.
- Perform a [search](/issues) to see if the enhancement has already been suggested. If it has, add a comment to the existing issue instead of opening a new one.
- Find out whether your idea fits with the scope and aims of the project. It's up to you to make a strong case to convince the project's developers of the merits of this feature. Keep in mind that we want features that will be useful to the majority of our users and not just a small subset. If you're just targeting a minority of users, consider writing an add-on/plugin library.
+17
View File
@@ -41,6 +41,7 @@
"eslint-plugin-react": "^7.34.1",
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react-refresh": "^0.4.6",
"prettier": "^3.3.3",
"vite": "^5.2.0"
}
},
@@ -5314,6 +5315,22 @@
"node": ">= 0.8.0"
}
},
"node_modules/prettier": {
"version": "3.3.3",
"resolved": "https://registry.npmjs.org/prettier/-/prettier-3.3.3.tgz",
"integrity": "sha512-i2tDNA0O5IrMO757lfrdQZCc2jPNDVntV0m/+4whiDfWaTKfMNgR7Qz0NAeGz/nRqF4m5/6CLzbP4/liHt12Ew==",
"dev": true,
"license": "MIT",
"bin": {
"prettier": "bin/prettier.cjs"
},
"engines": {
"node": ">=14"
},
"funding": {
"url": "https://github.com/prettier/prettier?sponsor=1"
}
},
"node_modules/prop-types": {
"version": "15.8.1",
"resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz",
+1
View File
@@ -43,6 +43,7 @@
"eslint-plugin-react": "^7.34.1",
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react-refresh": "^0.4.6",
"prettier": "^3.3.3",
"vite": "^5.2.0"
}
}
+2 -2
View File
@@ -1,7 +1,7 @@
.card {
padding: 2em;
padding: 2em;
}
.read-the-docs {
color: #888;
color: #888;
}
+56 -17
View File
@@ -70,7 +70,11 @@ function App() {
<ThemeProvider theme={mode === "light" ? lightTheme : darkTheme}>
<CssBaseline />
<Routes>
<Route exact path="/" element={<HomeLayout />}>
<Route
exact
path="/"
element={<HomeLayout />}
>
<Route
exact
path="/"
@@ -119,21 +123,34 @@ function App() {
/>
<Route
path="advanced-settings"
element={
<ProtectedRoute Component={AdvancedSettingsWithAdminProp} />
}
element={<ProtectedRoute Component={AdvancedSettingsWithAdminProp} />}
/>
<Route
path="account/profile"
element={<ProtectedRoute Component={Account} open="profile" />}
element={
<ProtectedRoute
Component={Account}
open="profile"
/>
}
/>
<Route
path="account/password"
element={<ProtectedRoute Component={Account} open="password" />}
element={
<ProtectedRoute
Component={Account}
open="password"
/>
}
/>
<Route
path="account/team"
element={<ProtectedRoute Component={Account} open="team" />}
element={
<ProtectedRoute
Component={Account}
open="team"
/>
}
/>
<Route
path="pagespeed"
@@ -145,9 +162,7 @@ function App() {
/>
<Route
path="pagespeed/:monitorId"
element={
<ProtectedRoute Component={PageSpeedDetailsWithAdminProp} />
}
element={<ProtectedRoute Component={PageSpeedDetailsWithAdminProp} />}
/>
<Route
path="pagespeed/configure/:monitorId"
@@ -155,15 +170,39 @@ function App() {
/>
</Route>
<Route exact path="/login" element={<Login />} />
<Route
exact
path="/login"
element={<Login />}
/>
<Route exact path="/register" element={<AdminCheckedRegister />} />
<Route exact path="/register/:token" element={<Register />} />
<Route
exact
path="/register"
element={<AdminCheckedRegister />}
/>
<Route
exact
path="/register/:token"
element={<Register />}
/>
{/* <Route path="/toast" element={<ToastComponent />} /> */}
<Route path="*" element={<NotFound />} />
<Route path="/forgot-password" element={<ForgotPassword />} />
<Route path="/check-email" element={<CheckEmail />} />
<Route path="/set-new-password/:token" element={<SetNewPassword />} />
<Route
path="*"
element={<NotFound />}
/>
<Route
path="/forgot-password"
element={<ForgotPassword />}
/>
<Route
path="/check-email"
element={<CheckEmail />}
/>
<Route
path="/set-new-password/:token"
element={<SetNewPassword />}
/>
<Route
path="/new-password-confirmed"
element={<NewPasswordConfirmed />}
+52 -81
View File
@@ -41,6 +41,9 @@ import ArrowUp from "../../assets/icons/up-arrow.svg?react";
import ArrowRight from "../../assets/icons/right-arrow.svg?react";
import ArrowLeft from "../../assets/icons/left-arrow.svg?react";
import DotsVertical from "../../assets/icons/dots-vertical.svg?react";
import ChangeLog from "../../assets/icons/changeLog.svg?react";
import Docs from "../../assets/icons/docs.svg?react";
import Folder from "../../assets/icons/folder.svg?react";
import "./index.css";
@@ -66,12 +69,30 @@ const menu = [
{ name: "Team", path: "account/team", icon: <TeamSvg /> },
],
},
{
name: "Other",
icon: <Folder />,
nested: [
{ name: "Settings", path: "settings", icon: <Settings /> },
{ name: "Support", path: "support", icon: <Support /> },
{ name: "Docs", path: "docs", icon: <Docs /> },
{ name: "Changelog", path: "changelog", icon: <ChangeLog /> },
],
},
];
const other = [
{ name: "Support", path: "support", icon: <Support /> },
{ name: "Settings", path: "settings", icon: <Settings /> },
];
const URL_MAP = {
support: "https://github.com/bluewave-labs/bluewave-uptime/issues",
docs: "https://bluewavelabs.gitbook.io/uptime-manager",
changelog: "https://github.com/bluewave-labs/bluewave-uptime/releases",
};
const PATH_MAP = {
monitors: "Dashboard",
pagespeed: "Dashboard",
account: "Account",
settings: "Other",
};
/**
* @component
@@ -87,7 +108,7 @@ function Sidebar() {
const dispatch = useDispatch();
const authState = useSelector((state) => state.auth);
const collapsed = useSelector((state) => state.ui.sidebar.collapsed);
const [open, setOpen] = useState({ Dashboard: false, Account: false });
const [open, setOpen] = useState({ Dashboard: false, Account: false, Other: false });
const [anchorEl, setAnchorEl] = useState(null);
const [popup, setPopup] = useState();
const { user } = useSelector((state) => state.auth);
@@ -120,13 +141,13 @@ function Sidebar() {
};
useEffect(() => {
if (
location.pathname.includes("monitors") ||
location.pathname.includes("pagespeed")
)
setOpen((prev) => ({ ...prev, Dashboard: true }));
else if (location.pathname.includes("/account"))
setOpen((prev) => ({ ...prev, Account: true }));
const matchedKey = Object.keys(PATH_MAP).find((key) =>
location.pathname.includes(key)
);
if (matchedKey) {
setOpen((prev) => ({ ...prev, [PATH_MAP[matchedKey]]: true }));
}
}, []);
return (
@@ -202,7 +223,9 @@ function Sidebar() {
},
}}
onClick={() => {
setOpen({ Dashboard: false, Account: false });
setOpen(prev =>
Object.fromEntries(Object.keys(prev).map(key => [key, false]))
)
dispatch(toggleSidebar());
}}
>
@@ -346,7 +369,12 @@ function Sidebar() {
}
key={child.path}
onClick={() => {
navigate(`/${child.path}`);
const url = URL_MAP[child.path];
if (url) {
window.open(url, "_blank", "noreferrer");
} else {
navigate(`/${child.path}`);
}
closePopup();
}}
sx={{
@@ -372,8 +400,8 @@ function Sidebar() {
<ListItemButton
onClick={() =>
setOpen((prev) => ({
...prev,
[`${item.name}`]: !prev[`${item.name}`],
...Object.fromEntries(Object.keys(prev).map(key => [key, false])),
[item.name]: !prev[item.name]
}))
}
sx={{
@@ -409,7 +437,14 @@ function Sidebar() {
: ""
}
key={child.path}
onClick={() => navigate(`/${child.path}`)}
onClick={() => {
const url = URL_MAP[child.path];
if (url) {
window.open(url, "_blank", "noreferrer");
} else {
navigate(`/${child.path}`);
}
}}
sx={{
gap: theme.spacing(4),
borderRadius: theme.shape.borderRadius,
@@ -455,70 +490,6 @@ function Sidebar() {
)
)}
</List>
<Divider sx={{ my: theme.spacing(4) }} />
{/* other */}
<List
component="nav"
aria-labelledby="nested-other-subheader"
subheader={
<ListSubheader
component="div"
id="nested-other-subheader"
sx={{
pt: theme.spacing(4),
px: collapsed ? 0 : theme.spacing(4),
backgroundColor: "transparent",
}}
>
Other
</ListSubheader>
}
sx={{ px: theme.spacing(6) }}
>
{other.map((item) => (
<Tooltip
key={item.path}
placement="right"
title={collapsed ? item.name : ""}
slotProps={{
popper: {
modifiers: [
{
name: "offset",
options: {
offset: [0, -16],
},
},
],
},
}}
disableInteractive
>
<ListItemButton
className={
location.pathname.includes(item.path) ? "selected-path" : ""
}
onClick={() =>
item.path === "support"
? window.open(
"https://github.com/bluewave-labs/bluewave-uptime/issues",
"_blank",
"noreferrer"
)
: navigate(`/${item.path}`)
}
sx={{
gap: theme.spacing(4),
borderRadius: theme.shape.borderRadius,
px: theme.spacing(4),
}}
>
<ListItemIcon sx={{ minWidth: 0 }}>{item.icon}</ListItemIcon>
<ListItemText>{item.name}</ListItemText>
</ListItemButton>
</Tooltip>
))}
</List>
<Divider sx={{ mt: "auto" }} />
<Stack
@@ -49,6 +49,7 @@ const TeamPanel = () => {
const [tableData, setTableData] = useState({});
const [members, setMembers] = useState([]);
const [filter, setFilter] = useState("all");
const [isDisabled, setIsDisabled] = useState(true);
const [errors, setErrors] = useState({});
const [isSendingInvite, setIsSendingInvite] = useState(false);
@@ -137,6 +138,9 @@ const TeamPanel = () => {
setTableData(data);
}, [members, filter]);
useEffect(() => {
setIsDisabled(Object.keys(errors).length !== 0 || toInvite.email === "");
}, [errors, toInvite.email]);
// RENAME ORGANIZATION
const toggleEdit = () => {
@@ -172,6 +176,10 @@ const TeamPanel = () => {
};
const handleInviteMember = async () => {
if (!toInvite.email) {
setErrors((prev) => ({ ...prev, email: "Email is required." }));
return;
}
setIsSendingInvite(true);
if (!toInvite.role.includes("user") || !toInvite.role.includes("admin"))
setToInvite((prev) => ({ ...prev, role: ["user"] }));
@@ -415,7 +423,7 @@ const TeamPanel = () => {
color="primary"
onClick={handleInviteMember}
loading={isSendingInvite}
disabled={Object.keys(errors).length !== 0}
disabled={isDisabled}
>
Send invite
</LoadingButton>
+35 -1
View File
@@ -3,6 +3,7 @@ import { useSelector, useDispatch } from "react-redux";
import { useTheme } from "@emotion/react";
import { useNavigate } from "react-router-dom";
import { createToast } from "../../../Utils/toastUtils";
import { logger } from "../../../Utils/Logger";
import {
Button,
IconButton,
@@ -14,6 +15,7 @@ import {
} from "@mui/material";
import {
deleteUptimeMonitor,
pauseUptimeMonitor,
getUptimeMonitorsByTeamId,
} from "../../../Features/UptimeMonitors/uptimeMonitorsSlice";
import Settings from "../../../assets/icons/settings-bold.svg?react";
@@ -26,6 +28,8 @@ const ActionsMenu = ({ monitor, isAdmin, updateCallback }) => {
const dispatch = useDispatch();
const theme = useTheme();
const authState = useSelector((state) => state.auth);
const authToken = authState.authToken;
const handleRemove = async (event) => {
event.preventDefault();
@@ -44,6 +48,24 @@ const ActionsMenu = ({ monitor, isAdmin, updateCallback }) => {
}
};
const handlePause = async () => {
try {
const action = await dispatch(
pauseUptimeMonitor({ authToken, monitorId: monitor._id })
);
if (pauseUptimeMonitor.fulfilled.match(action)) {
updateCallback();
const state = action?.payload?.data.isActive === false ? "paused" : "resumed";
createToast({ body: `Monitor ${state} successfully.` });
} else {
throw new Error(action?.error?.message ?? "Failed to pause monitor.");
}
} catch (error) {
logger.error("Error pausing monitor:", monitor._id, error);
createToast({ body: "Failed to pause monitor." });
}
};
const openMenu = (event, id, url) => {
event.preventDefault();
event.stopPropagation();
@@ -155,6 +177,17 @@ const ActionsMenu = ({ monitor, isAdmin, updateCallback }) => {
Clone
</MenuItem>
)}
{isAdmin && (
<MenuItem
onClick={(e) => {
e.stopPropagation();
handlePause(e);
}}
>
{monitor?.isActive === true ? "Pause" : "Resume"}
</MenuItem>
)}
{isAdmin && (
<MenuItem
onClick={(e) => {
@@ -164,7 +197,7 @@ const ActionsMenu = ({ monitor, isAdmin, updateCallback }) => {
>
Remove
</MenuItem>
)}
)}
</Menu>
<Modal
aria-labelledby="modal-delete-monitor"
@@ -238,6 +271,7 @@ ActionsMenu.propTypes = {
_id: PropTypes.string,
url: PropTypes.string,
type: PropTypes.string,
isActive: PropTypes.bool,
}).isRequired,
isAdmin: PropTypes.bool,
updateCallback: PropTypes.func,
+3
View File
@@ -0,0 +1,3 @@
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M17 17L22 12L17 7M7 7L2 12L7 17M14 3L10 21" stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 237 B

+3
View File
@@ -0,0 +1,3 @@
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M14 11H8M10 15H8M16 7H8M20 6.8V17.2C20 18.8802 20 19.7202 19.673 20.362C19.3854 20.9265 18.9265 21.3854 18.362 21.673C17.7202 22 16.8802 22 15.2 22H8.8C7.11984 22 6.27976 22 5.63803 21.673C5.07354 21.3854 4.6146 20.9265 4.32698 20.362C4 19.7202 4 18.8802 4 17.2V6.8C4 5.11984 4 4.27976 4.32698 3.63803C4.6146 3.07354 5.07354 2.6146 5.63803 2.32698C6.27976 2 7.11984 2 8.8 2H15.2C16.8802 2 17.7202 2 18.362 2.32698C18.9265 2.6146 19.3854 3.07354 19.673 3.63803C20 4.27976 20 5.11984 20 6.8Z" stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 684 B

+4
View File
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?><!-- Uploaded to: SVG Repo, www.svgrepo.com, Generator: SVG Repo Mixer Tools -->
<svg width="800px" height="800px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M3 8.2C3 7.07989 3 6.51984 3.21799 6.09202C3.40973 5.71569 3.71569 5.40973 4.09202 5.21799C4.51984 5 5.0799 5 6.2 5H9.67452C10.1637 5 10.4083 5 10.6385 5.05526C10.8425 5.10425 11.0376 5.18506 11.2166 5.29472C11.4184 5.4184 11.5914 5.59135 11.9373 5.93726L12.0627 6.06274C12.4086 6.40865 12.5816 6.5816 12.7834 6.70528C12.9624 6.81494 13.1575 6.89575 13.3615 6.94474C13.5917 7 13.8363 7 14.3255 7H17.8C18.9201 7 19.4802 7 19.908 7.21799C20.2843 7.40973 20.5903 7.71569 20.782 8.09202C21 8.51984 21 9.0799 21 10.2V15.8C21 16.9201 21 17.4802 20.782 17.908C20.5903 18.2843 20.2843 18.5903 19.908 18.782C19.4802 19 18.9201 19 17.8 19H6.2C5.07989 19 4.51984 19 4.09202 18.782C3.71569 18.5903 3.40973 18.2843 3.21799 17.908C3 17.4802 3 16.9201 3 15.8V8.2Z" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 1.0 KiB

+1 -1
View File
@@ -1,6 +1,6 @@
{
"all": true,
"include": ["**/*.js"],
"include": ["controllers/*.js"],
"exclude": ["**/*.test.js"],
"reporter": ["html", "text", "lcov"],
"sourceMap": false,
+7
View File
@@ -68,6 +68,7 @@ const registerUser = async (req, res, next) => {
}
const newUser = await req.db.insertUser({ ...req.body }, req.file);
logger.info(successMessages.AUTH_CREATE_USER, {
service: SERVICE_NAME,
userId: newUser._id,
@@ -78,7 +79,9 @@ const registerUser = async (req, res, next) => {
delete userForToken.avatarImage;
const appSettings = await req.settingsService.getSettings();
const token = issueToken(userForToken, appSettings);
req.emailService
.buildAndSendEmail(
"welcomeEmailTemplate",
@@ -99,6 +102,7 @@ const registerUser = async (req, res, next) => {
data: { user: newUser, token: token },
});
} catch (error) {
console.log("ERROR", error);
next(handleError(error, SERVICE_NAME, "registerController"));
}
};
@@ -293,6 +297,8 @@ const requestRecovery = async (req, res, next) => {
msg: successMessages.AUTH_CREATE_RECOVERY_TOKEN,
data: msgId,
});
} else {
throw new Error(errorMessages.FRIENDLY_ERROR);
}
} catch (error) {
next(handleError(error, SERVICE_NAME, "recoveryRequestController"));
@@ -435,6 +441,7 @@ const getAllUsers = async (req, res) => {
};
module.exports = {
issueToken,
registerUser,
loginUser,
editUser,
+2 -2
View File
@@ -6,8 +6,8 @@ const handleValidationError = (error, serviceName) => {
return error;
};
const handleError = (error, serviceName, method, code = 500) => {
error.code === undefined ? (error.code = code) : null;
const handleError = (error, serviceName, method, status = 500) => {
error.status === undefined ? (error.status = status) : null;
error.service === undefined ? (error.service = serviceName) : null;
error.method === undefined ? (error.method = method) : null;
return error;
+25 -15
View File
@@ -34,7 +34,7 @@ const dns = require('dns');
const getAllMonitors = async (req, res, next) => {
try {
const monitors = await req.db.getAllMonitors();
return res.json({
return res.status(200).json({
success: true,
msg: successMessages.MONITOR_GET_ALL,
data: monitors,
@@ -64,7 +64,7 @@ const getMonitorStatsById = async (req, res, next) => {
try {
const monitorStats = await req.db.getMonitorStatsById(req);
return res.json({
return res.status(200).json({
success: true,
msg: successMessages.MONITOR_STATS_BY_ID,
data: monitorStats,
@@ -87,7 +87,7 @@ const getMonitorCertificate = async (req, res, next) => {
const monitorUrl = new URL(monitor.url);
const certificate = await sslChecker(monitorUrl.hostname);
if (certificate && certificate.validTo) {
return res.json({
return res.status(200).json({
success: true,
msg: successMessages.MONITOR_CERTIFICATE,
data: {
@@ -95,7 +95,7 @@ const getMonitorCertificate = async (req, res, next) => {
},
});
} else {
return res.json({
return res.status(200).json({
success: true,
msg: successMessages.MONITOR_CERTIFICATE,
data: { certificateDate: "N/A" },
@@ -131,9 +131,10 @@ 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({
return res.status(200).json({
success: true,
msg: successMessages.MONITOR_GET_BY_ID,
data: monitor,
@@ -208,7 +209,7 @@ const getMonitorsByTeamId = async (req, res, next) => {
try {
const teamId = req.params.teamId;
const monitors = await req.db.getMonitorsByTeamId(req, res);
return res.json({
return res.status(200).json({
success: true,
msg: successMessages.MONITOR_GET_BY_USER_ID(teamId),
data: monitors,
@@ -362,14 +363,23 @@ const deleteAllMonitors = async (req, res, next) => {
const { jwtSecret } = req.settingsService.getSettings();
const { teamId } = jwt.verify(token, jwtSecret);
const { monitors, deletedCount } = await req.db.deleteAllMonitors(teamId);
await monitors.forEach(async (monitor) => {
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);
});
await Promise.all(
monitors.map(async (monitor) => {
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}`,
{
method: "deleteAllMonitors",
}
);
}
})
);
return res
.status(200)
.json({ success: true, msg: `Deleted ${deletedCount} monitors` });
@@ -497,7 +507,7 @@ const addDemoMonitors = async (req, res, next) => {
return res.status(200).json({
success: true,
message: successMessages.MONITOR_DEMO_ADDED,
msg: successMessages.MONITOR_DEMO_ADDED,
data: demoMonitors.length,
});
} catch (error) {
+18 -7
View File
@@ -1,13 +1,15 @@
const { handleError } = require("./controllerUtils");
const { errorMessages, successMessages } = require("../utils/messages");
const SERVICE_NAME = "JobQueueController";
const getMetrics = async (req, res, next) => {
try {
const metrics = await req.jobQueue.getMetrics();
res
.status(200)
.json({ success: true, msg: "Metrics retrieved", data: metrics });
res.status(200).json({
success: true,
msg: successMessages.QUEUE_GET_METRICS,
data: metrics,
});
} catch (error) {
next(handleError(error, SERVICE_NAME, "getMetrics"));
return;
@@ -17,7 +19,11 @@ const getMetrics = async (req, res, next) => {
const getJobs = async (req, res, next) => {
try {
const jobs = await req.jobQueue.getJobStats();
return res.status(200).json({ jobs });
return res.status(200).json({
success: true,
msg: successMessages.QUEUE_GET_METRICS,
data: jobs,
});
} catch (error) {
next(handleError(error, SERVICE_NAME, "getJobs"));
return;
@@ -27,7 +33,10 @@ const getJobs = async (req, res, next) => {
const addJob = async (req, res, next) => {
try {
await req.jobQueue.addJob(Math.random().toString(36).substring(7));
return res.send("Added job");
return res.status(200).json({
success: true,
msg: successMessages.QUEUE_ADD_JOB,
});
} catch (error) {
next(handleError(error, SERVICE_NAME, "addJob"));
return;
@@ -37,7 +46,9 @@ const addJob = async (req, res, next) => {
const obliterateQueue = async (req, res, next) => {
try {
await req.jobQueue.obliterate();
return res.status(200).send("Obliterated queue");
return res
.status(200)
.json({ success: true, msg: successMessages.QUEUE_OBLITERATE });
} catch (error) {
next(handleError(error, SERVICE_NAME, "obliterateQueue"));
return;
+99
View File
@@ -36,6 +36,7 @@
"devDependencies": {
"nodemon": "3.1.0",
"nyc": "17.1.0",
"proxyquire": "2.1.3",
"sinon": "19.0.2"
}
},
@@ -2802,6 +2803,20 @@
"resolved": "https://registry.npmjs.org/fecha/-/fecha-4.2.3.tgz",
"integrity": "sha512-OP2IUU6HeYKJi3i0z4A19kHMQoLVs4Hc+DPqqxI2h/DPZHTm/vjsfC6P0b4jCMy14XizLBqvndQ+UilD7707Jw=="
},
"node_modules/fill-keys": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/fill-keys/-/fill-keys-1.0.2.tgz",
"integrity": "sha512-tcgI872xXjwFF4xgQmLxi76GnwJG3g/3isB1l4/G5Z4zrbddGpBjqZCO9oEAcB5wX0Hj/5iQB3toxfO7in1hHA==",
"dev": true,
"license": "MIT",
"dependencies": {
"is-object": "~1.0.1",
"merge-descriptors": "~1.0.0"
},
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/fill-range": {
"version": "7.1.1",
"resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz",
@@ -3535,6 +3550,22 @@
"node": ">=8"
}
},
"node_modules/is-core-module": {
"version": "2.15.1",
"resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.15.1.tgz",
"integrity": "sha512-z0vtXSwucUJtANQWldhbtbt7BnL0vxiFjIdDLAatwhDYty2bad6s+rijD6Ri4YuYJubLzIJLUidCh09e1djEVQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"hasown": "^2.0.2"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/is-extglob": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz",
@@ -3575,6 +3606,16 @@
"node": ">=0.12.0"
}
},
"node_modules/is-object": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/is-object/-/is-object-1.0.2.tgz",
"integrity": "sha512-2rRIahhZr2UWb45fIOuvZGpFtz0TyOZLf32KxBbSoUCeZR495zCKlWUKKUByk3geS2eAs7ZAABt0Y/Rx0GiQGA==",
"dev": true,
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/is-plain-obj": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-2.1.0.tgz",
@@ -4968,6 +5009,13 @@
"node": ">=10"
}
},
"node_modules/module-not-found-error": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/module-not-found-error/-/module-not-found-error-1.0.1.tgz",
"integrity": "sha512-pEk4ECWQXV6z2zjhRZUongnLJNUeGQJ3w6OQ5ctGwD+i5o93qjRQUk2Rt6VdNeu3sEP0AB4LcfvdebpxBRVr4g==",
"dev": true,
"license": "MIT"
},
"node_modules/mongodb": {
"version": "6.6.2",
"resolved": "https://registry.npmjs.org/mongodb/-/mongodb-6.6.2.tgz",
@@ -5833,6 +5881,13 @@
"node": ">=8"
}
},
"node_modules/path-parse": {
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz",
"integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==",
"dev": true,
"license": "MIT"
},
"node_modules/path-scurry": {
"version": "1.11.1",
"resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-1.11.1.tgz",
@@ -6499,6 +6554,7 @@
"version": "3.3.3",
"resolved": "https://registry.npmjs.org/prettier/-/prettier-3.3.3.tgz",
"integrity": "sha512-i2tDNA0O5IrMO757lfrdQZCc2jPNDVntV0m/+4whiDfWaTKfMNgR7Qz0NAeGz/nRqF4m5/6CLzbP4/liHt12Ew==",
"license": "MIT",
"bin": {
"prettier": "bin/prettier.cjs"
},
@@ -6545,6 +6601,18 @@
"resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz",
"integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg=="
},
"node_modules/proxyquire": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/proxyquire/-/proxyquire-2.1.3.tgz",
"integrity": "sha512-BQWfCqYM+QINd+yawJz23tbBM40VIGXOdDw3X344KcclI/gtBbdWF6SlQ4nK/bYhF9d27KYug9WzljHC6B9Ysg==",
"dev": true,
"license": "MIT",
"dependencies": {
"fill-keys": "^1.0.2",
"module-not-found-error": "^1.0.1",
"resolve": "^1.11.1"
}
},
"node_modules/pstree.remy": {
"version": "1.1.8",
"resolved": "https://registry.npmjs.org/pstree.remy/-/pstree.remy-1.1.8.tgz",
@@ -6683,6 +6751,24 @@
"dev": true,
"license": "ISC"
},
"node_modules/resolve": {
"version": "1.22.8",
"resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.8.tgz",
"integrity": "sha512-oKWePCxqpd6FlLvGV1VU0x7bkPmmCNolxzjMf4NczoDnQcIWrAF+cPtZn5i6n+RfD2d9i0tzpKnG6Yk168yIyw==",
"dev": true,
"license": "MIT",
"dependencies": {
"is-core-module": "^2.13.0",
"path-parse": "^1.0.7",
"supports-preserve-symlinks-flag": "^1.0.0"
},
"bin": {
"resolve": "bin/resolve"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/resolve-from": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz",
@@ -7242,6 +7328,19 @@
"node": ">=4"
}
},
"node_modules/supports-preserve-symlinks-flag": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz",
"integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/svgo": {
"version": "3.3.2",
"resolved": "https://registry.npmjs.org/svgo/-/svgo-3.3.2.tgz",
+43 -41
View File
@@ -1,43 +1,45 @@
{
"name": "server",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "nyc mocha",
"dev": "nodemon index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"@sendgrid/mail": "^8.1.3",
"axios": "^1.7.2",
"bcrypt": "^5.1.1",
"bullmq": "5.7.15",
"chai": "5.1.1",
"cors": "^2.8.5",
"dotenv": "^16.4.5",
"express": "^4.19.2",
"handlebars": "^4.7.8",
"helmet": "^7.1.0",
"joi": "^17.13.1",
"jsonwebtoken": "9.0.2",
"mailersend": "^2.2.0",
"mjml": "^5.0.0-alpha.4",
"mocha": "10.7.3",
"mongoose": "^8.3.3",
"multer": "1.4.5-lts.1",
"nodemailer": "^6.9.14",
"ping": "0.4.4",
"sharp": "0.33.4",
"ssl-checker": "2.0.10",
"swagger-ui-express": "5.0.1",
"winston": "^3.13.0"
},
"devDependencies": {
"nodemon": "3.1.0",
"nyc": "17.1.0",
"sinon": "19.0.2"
}
"name": "server",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "nyc mocha",
"dev": "nodemon index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"@sendgrid/mail": "^8.1.3",
"axios": "^1.7.2",
"bcrypt": "^5.1.1",
"bullmq": "5.7.15",
"chai": "5.1.1",
"cors": "^2.8.5",
"dotenv": "^16.4.5",
"express": "^4.19.2",
"handlebars": "^4.7.8",
"helmet": "^7.1.0",
"joi": "^17.13.1",
"jsonwebtoken": "9.0.2",
"mailersend": "^2.2.0",
"mjml": "^5.0.0-alpha.4",
"mocha": "10.7.3",
"mongoose": "^8.3.3",
"multer": "1.4.5-lts.1",
"nodemailer": "^6.9.14",
"ping": "0.4.4",
"sharp": "0.33.4",
"ssl-checker": "2.0.10",
"swagger-ui-express": "5.0.1",
"winston": "^3.13.0"
},
"devDependencies": {
"nodemon": "3.1.0",
"prettier": "^3.3.3",
"nyc": "17.1.0",
"proxyquire": "2.1.3",
"sinon": "19.0.2"
}
}
+12 -27
View File
@@ -7,39 +7,24 @@ const upload = multer();
const User = require("../db/models/User");
const {
registerUser,
loginUser,
editUser,
requestRecovery,
validateRecovery,
resetPassword,
checkSuperadminExists,
getAllUsers,
deleteUser,
registerUser,
loginUser,
editUser,
requestRecovery,
validateRecovery,
resetPassword,
checkSuperadminExists,
getAllUsers,
deleteUser,
} = require("../controllers/authController");
//Auth routes
router.post("/register", upload.single("profileImage"), registerUser);
router.post("/login", loginUser);
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",
verifyJWT,
isAllowed(["admin", "superadmin"]),
getAllUsers
);
router.delete(
"/user/:userId",
verifyJWT,
verifyOwnership(User, "userId"),
deleteUser
);
router.get("/users", verifyJWT, isAllowed(["admin", "superadmin"]), getAllUsers);
router.delete("/user/:userId", verifyJWT, verifyOwnership(User, "userId"), deleteUser);
//Recovery routes
router.post("/recovery/request", requestRecovery);
+260 -67
View File
@@ -1,4 +1,5 @@
const {
issueToken,
registerUser,
loginUser,
editUser,
@@ -12,11 +13,45 @@ const {
const jwt = require("jsonwebtoken");
const { errorMessages, successMessages } = require("../../utils/messages");
const sinon = require("sinon");
const logger = require("../../utils/logger");
describe("Auth Controller - issueToken", () => {
it("should reject with an error if jwt.sign fails", () => {
const error = new Error("jwt.sign error");
stub = sinon.stub(jwt, "sign").throws(error);
const payload = { id: "123" };
const appSettings = { jwtSecret: "my_secret" };
expect(() => issueToken(payload, appSettings)).to.throw(error);
stub.restore();
});
it("should return a token if jwt.sign is successful and appSettings.jtwTTL is not defined", () => {
const payload = { id: "123" };
const appSettings = { jwtSecret: "my_secret" };
const token = issueToken(payload, appSettings);
expect(token).to.be.a("string");
});
it("should return a token if jwt.sign is successful and appSettings.jwtTTL is defined", () => {
const payload = { id: "123" };
const appSettings = { jwtSecret: "my_secret", jwtTTL: "1s" };
const token = issueToken(payload, appSettings);
expect(token).to.be.a("string");
});
});
describe("Auth Controller - registerUser", () => {
// Set up test
beforeEach(() => {
req = {
body: {
firstName: "firstname",
lastName: "lastname",
email: "test@test.com",
password: "Uptime1!",
role: ["admin"],
teamId: "123",
inviteToken: "invite",
},
db: {
checkSuperadmin: sinon.stub(),
getInviteTokenAndDelete: sinon.stub(),
@@ -29,7 +64,7 @@ describe("Auth Controller - registerUser", () => {
}),
},
emailService: {
buildAndSendEmail: sinon.stub().returns(Promise.resolve()),
buildAndSendEmail: sinon.stub(),
},
file: {},
};
@@ -38,72 +73,97 @@ describe("Auth Controller - registerUser", () => {
json: sinon.stub(),
};
next = sinon.stub();
sinon.stub(logger, "error");
});
afterEach(() => {
sinon.restore();
});
it("should register a valid user", async () => {
req.body = {
firstName: "John",
lastName: "Doe",
email: "john.doe@example.com",
password: "Uptime1!",
inviteToken: "someToken",
role: ["user"],
teamId: "123",
};
req.db.checkSuperadmin.resolves(false);
req.db.insertUser.resolves({
_id: "123",
_doc: {
firstName: "John",
lastName: "Doe",
email: "john.doe@example.com",
},
});
it("should reject with an error if body validation fails", async () => {
req.body = {};
await registerUser(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422);
});
it("should reject with an error if checkSuperadmin fails", async () => {
req.db.checkSuperadmin.rejects(new Error("checkSuperadmin error"));
await registerUser(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("checkSuperadmin error");
});
it("should reject with an error if getInviteTokenAndDelete fails", async () => {
req.db.checkSuperadmin.resolves(true);
req.db.getInviteTokenAndDelete.rejects(
new Error("getInviteTokenAndDelete error")
);
await registerUser(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal(
"getInviteTokenAndDelete error"
);
});
it("should reject with an error if updateAppSettings fails", async () => {
req.db.checkSuperadmin.resolves(false);
req.db.updateAppSettings.rejects(new Error("updateAppSettings error"));
await registerUser(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("updateAppSettings error");
});
it("should reject with an error if insertUser fails", async () => {
req.db.checkSuperadmin.resolves(false);
req.db.updateAppSettings.resolves();
req.db.insertUser.rejects(new Error("insertUser error"));
await registerUser(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("insertUser error");
});
it("should reject with an error if settingsService.getSettings fails", async () => {
req.db.checkSuperadmin.resolves(false);
req.db.updateAppSettings.resolves();
req.db.insertUser.resolves({ _id: "123" });
req.settingsService.getSettings.rejects(
new Error("settingsService.getSettings error")
);
await registerUser(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 log an error if emailService.buildAndSendEmail fails", async () => {
req.db.checkSuperadmin.resolves(false);
req.db.updateAppSettings.resolves();
req.db.insertUser.returns({ _id: "123" });
req.settingsService.getSettings.returns({ jwtSecret: "my_secret" });
req.emailService.buildAndSendEmail.rejects(new Error("emailService error"));
await registerUser(req, res, next);
expect(logger.error.calledOnce).to.be.true;
expect(logger.error.firstCall.args[1].error).to.equal("emailService error");
});
it("should return a success message and data if all operations are successful", async () => {
const user = { _id: "123" };
req.db.checkSuperadmin.resolves(false);
req.db.updateAppSettings.resolves();
req.db.insertUser.returns(user);
req.settingsService.getSettings.returns({ jwtSecret: "my_secret" });
req.emailService.buildAndSendEmail.resolves("message-id");
await registerUser(req, res, next);
expect(res.status.calledWith(200)).to.be.true;
expect(
res.json.calledWith(
sinon.match({
success: true,
msg: sinon.match.string,
data: {
user: sinon.match.object,
token: sinon.match.string,
},
})
)
res.json.calledWith({
success: true,
msg: successMessages.AUTH_CREATE_USER,
data: { user, token: sinon.match.string },
})
).to.be.true;
expect(next.notCalled).to.be.true;
});
it("should reject a user with an invalid password", async () => {
req.body = {
firstName: "John",
lastName: "Doe",
email: "john.doe@example.com",
password: "bad_password",
inviteToken: "someToken",
role: ["user"],
teamId: "123",
};
await registerUser(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422);
});
it("should reject a user with an invalid role", async () => {
req.body = {
firstName: "John",
lastName: "Doe",
email: "john.doe@example.com",
password: "Uptime1!",
inviteToken: "someToken",
role: ["superman"],
teamId: "123",
};
await registerUser(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422);
});
});
describe("Auth Controller - loginUser", () => {
@@ -131,6 +191,20 @@ describe("Auth Controller - loginUser", () => {
comparePassword: sinon.stub(),
};
});
it("should reject with an error if validation fails", async () => {
req.body = {};
await loginUser(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422);
});
it("should reject with an error if getUserByEmail fails", async () => {
req.db.getUserByEmail.rejects(new Error("getUserByEmail error"));
await loginUser(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("getUserByEmail error");
});
it("should login user successfully", async () => {
req.db.getUserByEmail.resolves(user);
user.comparePassword.resolves(true);
@@ -186,10 +260,63 @@ describe("Auth Controller - editUser", async () => {
json: sinon.stub(),
};
next = sinon.stub();
stub = sinon.stub(jwt, "verify").returns({ email: "test@example.com" });
});
afterEach(() => {
sinon.restore();
stub.restore();
});
it("should reject with an error if param validation fails", async () => {
req.params = {};
await editUser(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422);
});
it("should reject with an error if body validation fails", async () => {
req.body = { invalid: 1 };
await editUser(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422);
});
it("should reject with an error if param.userId !== req.user._id", async () => {
req.params = { userId: "456" };
await editUser(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(401);
});
it("should reject with an error if !req.body.password and getUserByEmail fails", async () => {
req.db.getUserByEmail.rejects(new Error("getUserByEmail error"));
await editUser(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("getUserByEmail error");
});
it("should reject with an error if user.comparePassword fails", async () => {
req.db.getUserByEmail.returns({
comparePassword: sinon.stub().rejects(new Error("Bad Password Match")),
});
await editUser(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("Bad Password Match");
});
it("should reject with an error if user.comparePassword returns false", async () => {
req.db.getUserByEmail.returns({
comparePassword: sinon.stub().returns(false),
});
await editUser(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(403);
expect(next.firstCall.args[0].message).to.equal(
errorMessages.AUTH_INCORRECT_PASSWORD
);
});
it("should edit a user if it receives a proper request", async () => {
sinon.stub(jwt, "verify").returns({ email: "test@example.com" });
const user = {
comparePassword: sinon.stub().resolves(true),
};
@@ -211,6 +338,24 @@ describe("Auth Controller - editUser", async () => {
expect(next.notCalled).to.be.true;
});
it("should edit a user if it receives a proper request and both password fields are undefined", async () => {
req.body.password = undefined;
req.body.newPassword = undefined;
req.db.getUserByEmail.resolves(user);
req.db.updateUser.resolves({ email: "test@example.com" });
await editUser(req, res, next);
expect(res.status.calledWith(200)).to.be.true;
expect(
res.json.calledWith({
success: true,
msg: successMessages.AUTH_UPDATE_USER,
data: { email: "test@example.com" },
})
).to.be.true;
expect(next.notCalled).to.be.true;
});
it("should reject an edit request if password format is incorrect", async () => {
req.body = { password: "bad_password", newPassword: "bad_password" };
const user = {
@@ -239,6 +384,13 @@ describe("Auth Controller - checkSuperadminExists", async () => {
next = sinon.stub();
});
it("should reject with an error if checkSuperadmin fails", async () => {
req.db.checkSuperadmin.rejects(new Error("checkSuperadmin error"));
await checkSuperadminExists(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("checkSuperadmin error");
});
it("should return true if a superadmin exists", async () => {
req.db.checkSuperadmin.resolves(true);
await checkSuperadminExists(req, res, next);
@@ -289,6 +441,30 @@ describe("Auth Controller - requestRecovery", async () => {
};
next = sinon.stub();
});
it("should reject with an error if validation fails", async () => {
req.body = {};
await requestRecovery(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422);
});
it("should reject with an error if getUserByEmail fails", async () => {
req.db.getUserByEmail.rejects(new Error("getUserByEmail error"));
await requestRecovery(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("getUserByEmail error");
});
it("should throw an error if the user is not found", async () => {
req.db.getUserByEmail.resolves(null);
await requestRecovery(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
// expect(next.firstCall.args[0].message).to.equal(
// errorMessages.FRIENDLY_ERROR
// );
});
it("should throw an error if the email is not provided", async () => {
req.body = {};
await requestRecovery(req, res, next);
@@ -344,15 +520,24 @@ describe("Auth Controller - validateRecovery", async () => {
next = sinon.stub();
});
it("should call next with a validation error if the token is invalid", async () => {
req = {
body: {},
};
it("should reject with an error if validation fails", async () => {
req.body = {};
await validateRecovery(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422);
});
it("should reject with an error if validateRecoveryToken fails", async () => {
req.db.validateRecoveryToken.rejects(
new Error("validateRecoveryToken error")
);
await validateRecovery(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal(
"validateRecoveryToken error"
);
});
it("should return a success message if the token is valid", async () => {
req.db.validateRecoveryToken.resolves();
await validateRecovery(req, res, next);
@@ -391,14 +576,23 @@ describe("Auth Controller - resetPassword", async () => {
};
handleValidationError = sinon.stub();
handleError = sinon.stub();
issueToken = sinon.stub();
});
it("should call next with a validation error if the password is invalid", async () => {
it("should reject with an error if validation fails", async () => {
req.body = { password: "bad_password" };
await resetPassword(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422);
});
it("should reject with an error if resetPassword fails", async () => {
const error = new Error("resetPassword error");
newPasswordValidation.validateAsync.resolves();
req.db.resetPassword.rejects(error);
await resetPassword(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("resetPassword error");
});
it("should reset password successfully", async () => {
const user = { _doc: {} };
const appSettings = { jwtSecret: "my_secret" };
@@ -407,7 +601,6 @@ describe("Auth Controller - resetPassword", async () => {
newPasswordValidation.validateAsync.resolves();
req.db.resetPassword.resolves(user);
req.settingsService.getSettings.resolves(appSettings);
issueToken.returns(token);
await resetPassword(req, res, next);
@@ -45,22 +45,22 @@ describe("controllerUtils - handleValidationError", () => {
});
describe("handleError", () => {
it("should set code to the provided code if error.code is undefined", () => {
it("should set stats to the provided status if error.code is undefined", () => {
const error = {};
const serviceName = "TestService";
const method = "testMethod";
const code = 400;
const result = handleError(error, serviceName, method, code);
expect(result.code).to.equal(code);
const status = 400;
const result = handleError(error, serviceName, method, status);
expect(result.status).to.equal(status);
});
it("should not overwrite error.code if it is already defined", () => {
const error = { code: 404 };
const error = { status: 404 };
const serviceName = "TestService";
const method = "testMethod";
const code = 400;
const result = handleError(error, serviceName, method, code);
expect(result.code).to.equal(404);
const status = 400;
const result = handleError(error, serviceName, method, status);
expect(result.status).to.equal(404);
});
it("should set service to the provided serviceName if error.service is undefined", () => {
@@ -100,6 +100,6 @@ describe("handleError", () => {
const serviceName = "TestService";
const method = "testMethod";
const result = handleError(error, serviceName, method);
expect(result.code).to.equal(500);
expect(result.status).to.equal(500);
});
});
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,168 @@
const { afterEach } = require("node:test");
const {
getMetrics,
getJobs,
addJob,
obliterateQueue,
} = require("../../controllers/queueController");
const SERVICE_NAME = "JobQueueController";
const { errorMessages, successMessages } = require("../../utils/messages");
const sinon = require("sinon");
describe("Queue Controller - getMetrics", () => {
beforeEach(() => {
req = {
headers: {},
params: {},
body: {},
db: {},
jobQueue: {
getMetrics: sinon.stub(),
},
};
res = {
status: sinon.stub().returnsThis(),
json: sinon.stub(),
};
next = sinon.stub();
handleError = sinon.stub();
});
afterEach(() => {
sinon.restore();
});
it("should throw an error if getMetrics throws an error", async () => {
req.jobQueue.getMetrics.throws(new Error("getMetrics error"));
await getMetrics(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("getMetrics error");
});
it("should return a success message and data if getMetrics is successful", async () => {
const data = { data: "metrics" };
req.jobQueue.getMetrics.returns(data);
await getMetrics(req, res, next);
expect(res.status.firstCall.args[0]).to.equal(200);
expect(res.json.firstCall.args[0]).to.deep.equal({
success: true,
msg: successMessages.QUEUE_GET_METRICS,
data,
});
});
});
describe("Queue Controller - getJobs", () => {
beforeEach(() => {
req = {
headers: {},
params: {},
body: {},
db: {},
jobQueue: {
getJobStats: sinon.stub(),
},
};
res = {
status: sinon.stub().returnsThis(),
json: sinon.stub(),
};
next = sinon.stub();
handleError = sinon.stub();
});
afterEach(() => {
sinon.restore();
});
it("should reject with an error if getJobs throws an error", async () => {
req.jobQueue.getJobStats.throws(new Error("getJobs error"));
await getJobs(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("getJobs error");
});
it("should return a success message and data if getJobs is successful", async () => {
const data = { data: "jobs" };
req.jobQueue.getJobStats.returns(data);
await getJobs(req, res, next);
expect(res.status.firstCall.args[0]).to.equal(200);
expect(res.json.firstCall.args[0]).to.deep.equal({
success: true,
msg: successMessages.QUEUE_GET_METRICS,
data,
});
});
});
describe("Queue Controller - addJob", () => {
beforeEach(() => {
req = {
headers: {},
params: {},
body: {},
db: {},
jobQueue: {
addJob: sinon.stub(),
},
};
res = {
status: sinon.stub().returnsThis(),
json: sinon.stub(),
};
next = sinon.stub();
handleError = sinon.stub();
});
afterEach(() => {
sinon.restore();
});
it("should reject with an error if addJob throws an error", async () => {
req.jobQueue.addJob.throws(new Error("addJob error"));
await addJob(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("addJob error");
});
it("should return a success message if addJob is successful", async () => {
req.jobQueue.addJob.resolves();
await addJob(req, res, next);
expect(res.status.firstCall.args[0]).to.equal(200);
expect(res.json.firstCall.args[0]).to.deep.equal({
success: true,
msg: successMessages.QUEUE_ADD_JOB,
});
});
});
describe("Queue Controller - obliterateQueue", () => {
beforeEach(() => {
req = {
headers: {},
params: {},
body: {},
db: {},
jobQueue: {
obliterate: sinon.stub(),
},
};
res = {
status: sinon.stub().returnsThis(),
json: sinon.stub(),
};
next = sinon.stub();
handleError = sinon.stub();
});
afterEach(() => {
sinon.restore();
});
it("should reject with an error if obliterateQueue throws an error", async () => {
req.jobQueue.obliterate.throws(new Error("obliterateQueue error"));
await obliterateQueue(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("obliterateQueue error");
});
it("should return a success message if obliterateQueue is successful", async () => {
req.jobQueue.obliterate.resolves();
await obliterateQueue(req, res, next);
expect(res.status.firstCall.args[0]).to.equal(200);
expect(res.json.firstCall.args[0]).to.deep.equal({
success: true,
msg: successMessages.QUEUE_OBLITERATE,
});
});
});
@@ -0,0 +1,105 @@
const { afterEach } = require("node:test");
const {
getAppSettings,
updateAppSettings,
} = require("../../controllers/settingsController");
const { errorMessages, successMessages } = require("../../utils/messages");
const sinon = require("sinon");
describe("Settings Controller - getAppSettings", () => {
beforeEach(() => {
req = {
headers: {},
params: {},
body: {},
db: {},
settingsService: {
getSettings: sinon.stub(),
},
};
res = {
status: sinon.stub().returnsThis(),
json: sinon.stub(),
};
next = sinon.stub();
handleError = sinon.stub();
});
afterEach(() => {
sinon.restore();
});
it("should throw an error if getSettings throws an error", async () => {
req.settingsService.getSettings.throws(new Error("getSettings error"));
await getAppSettings(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("getSettings error");
});
it("should return a success message and data if getSettings is successful", async () => {
const data = { data: "settings" };
req.settingsService.getSettings.returns(data);
await getAppSettings(req, res, next);
expect(res.status.firstCall.args[0]).to.equal(200);
expect(res.json.firstCall.args[0]).to.deep.equal({
success: true,
msg: successMessages.GET_APP_SETTINGS,
data,
});
});
});
describe("Settings Controller - updateAppSettings", () => {
beforeEach(() => {
req = {
headers: {},
params: {},
body: {},
db: {
updateAppSettings: sinon.stub(),
},
settingsService: {
reloadSettings: sinon.stub(),
},
};
res = {
status: sinon.stub().returnsThis(),
json: sinon.stub(),
};
next = sinon.stub();
handleError = sinon.stub();
});
afterEach(() => {
sinon.restore();
});
it("should reject with an error if body validation fails", async () => {
req.body = { invalid: 1 };
await updateAppSettings(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(422);
});
it("should reject with an error if updateAppSettings throws an error", async () => {
req.db.updateAppSettings.throws(new Error("updateAppSettings error"));
await updateAppSettings(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("updateAppSettings error");
});
it("should reject with an error if reloadSettings throws an error", async () => {
req.settingsService.reloadSettings.throws(
new Error("reloadSettings error")
);
await updateAppSettings(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("reloadSettings error");
});
it("should return a success message and data if updateAppSettings is successful", async () => {
const data = { data: "settings" };
req.settingsService.reloadSettings.returns(data);
await updateAppSettings(req, res, next);
expect(res.status.firstCall.args[0]).to.equal(200);
expect(res.json.firstCall.args[0]).to.deep.equal({
success: true,
msg: successMessages.UPDATE_APP_SETTINGS,
data,
});
});
});
+6
View File
@@ -86,6 +86,12 @@ const successMessages = {
MONITOR_CERTIFICATE: "Got monitor certificate successfully",
MONITOR_DEMO_ADDED: "Successfully added demo monitors",
// Queue Controller
QUEUE_GET_METRICS: "Got metrics successfully",
QUEUE_GET_METRICS: "Got job stats successfully",
QUEUE_ADD_JOB: "Job added successfully",
QUEUE_OBLITERATE: "Queue obliterated",
//Job Queue
JOB_QUEUE_DELETE_JOB: "Job removed successfully",
JOB_QUEUE_OBLITERATE: "Queue OBLITERATED!!!",
+1 -1
View File
@@ -128,7 +128,7 @@ From the `Docker` directory run
---
#### Starting the development derver <a href="#start-server" id="start-server"></a>
#### Starting the development server <a href="#start-server" id="start-server"></a>
- run `npm run dev` to start the development server
+1 -1
View File
@@ -128,7 +128,7 @@ From the `Docker` directory run
---
#### Starting the development derver <a href="#start-server" id="start-server"></a>
#### Starting the development server <a href="#start-server" id="start-server"></a>
- run `npm run dev` to start the development server
+1 -1
View File
@@ -128,7 +128,7 @@ From the `Docker` directory run
---
#### Starting the development derver <a href="#start-server" id="start-server"></a>
#### Starting the development server <a href="#start-server" id="start-server"></a>
- run `npm run dev` to start the development server