Merge pull request #2232 from bluewave-labs/feat/email-settings

feat: email settings
This commit is contained in:
Alexander Holliday authored and GitHub committed 2025-05-10 16:13:35 -07:00
commit 38f52af0f0
14 files changed
+247 -75

No files matched your search

+2 -2
View File
@@ -3,7 +3,7 @@ import { networkService } from "../main";
import { createToast } from "../Utils/toastUtils";
import { useTranslation } from "react-i18next";
const useFetchSettings = ({ setSettings }) => {
const useFetchSettings = ({ setSettingsData }) => {
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState(undefined);
useEffect(() => {
@@ -11,7 +11,7 @@ const useFetchSettings = ({ setSettings }) => {
setIsLoading(true);
try {
const response = await networkService.getAppSettings();
setSettings(response?.data?.data);
setSettingsData(response?.data?.data);
} catch (error) {
createToast({ body: "Failed to fetch settings" });
setError(error);
@@ -8,12 +8,8 @@ import { PropTypes } from "prop-types";
import { useTranslation } from "react-i18next";
import Dialog from "../../Components/Dialog";
import { useState } from "react";
const SettingsDemoMonitors = ({
isLoading,
authIsLoading,
checksIsLoading,
handleChange,
}) => {
const SettingsDemoMonitors = ({ HEADER_SX, handleChange, isLoading }) => {
const { t } = useTranslation();
const theme = useTheme();
// Local state
@@ -23,16 +19,14 @@ const SettingsDemoMonitors = ({
<ConfigBox>
<Box>
<Typography component="h1">{t("settingsDemoMonitors")}</Typography>
<Typography sx={{ mt: theme.spacing(2) }}>
{t("settingsDemoMonitorsDescription")}
</Typography>
<Typography sx={HEADER_SX}>{t("settingsDemoMonitorsDescription")}</Typography>
</Box>
<Box>
<Typography>{t("settingsAddDemoMonitors")}</Typography>
<Button
variant="contained"
color="accent"
loading={isLoading || authIsLoading || checksIsLoading}
loading={isLoading}
onClick={() => {
const syntheticEvent = {
target: {
@@ -59,7 +53,7 @@ const SettingsDemoMonitors = ({
<Button
variant="contained"
color="error"
loading={isLoading || authIsLoading || checksIsLoading}
loading={isLoading}
onClick={() => setIsOpen(true)}
sx={{ mt: theme.spacing(4) }}
>
@@ -81,7 +75,7 @@ const SettingsDemoMonitors = ({
handleChange(syntheticEvent);
setIsOpen(false);
}}
isLoading={isLoading || authIsLoading || checksIsLoading}
isLoading={isLoading}
/>
</ConfigBox>
</>
@@ -89,10 +83,8 @@ const SettingsDemoMonitors = ({
};
SettingsDemoMonitors.propTypes = {
isLoading: PropTypes.bool,
authIsLoading: PropTypes.bool,
checksIsLoading: PropTypes.bool,
handleChange: PropTypes.func,
HEADER_SX: PropTypes.object,
};
export default SettingsDemoMonitors;
+126
View File
@@ -0,0 +1,126 @@
import Box from "@mui/material/Box";
import Typography from "@mui/material/Typography";
import ConfigBox from "../../Components/ConfigBox";
import TextInput from "../../Components/Inputs/TextInput";
import Button from "@mui/material/Button";
import Stack from "@mui/material/Stack";
// Utils
import { useTheme } from "@emotion/react";
import { PropTypes } from "prop-types";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { PasswordEndAdornment } from "../../Components/Inputs/TextInput/Adornments";
const SettingsEmail = ({
HEADER_SX,
handleChange,
settingsData,
setSettingsData,
isPasswordSet,
}) => {
const { t } = useTranslation();
const theme = useTheme();
const [password, setPassword] = useState("");
const [hasBeenReset, setHasBeenReset] = useState(false);
const handlePasswordChange = (e) => {
setPassword(e.target.value);
setSettingsData({
...settingsData,
settings: { ...settingsData.settings, systemEmailPassword: e.target.value },
});
};
return (
<ConfigBox>
<Box>
<Typography component="h1">{t("settingsEmail")}</Typography>
<Typography sx={HEADER_SX}>{t("settingsEmailDescription")}</Typography>
</Box>
<Box>
<Stack gap={theme.spacing(10)}>
<Box>
<Typography>{t("settingsEmailHost")}</Typography>
<TextInput
name="systemEmailHost"
placeholder="smtp.gmail.com"
value={settingsData?.settings?.systemEmailHost ?? ""}
onChange={handleChange}
/>
</Box>
<Box>
<Typography>{t("settingsEmailPort")}</Typography>
<TextInput
name="systemEmailPort"
placeholder="425"
type="number"
value={settingsData?.settings?.systemEmailPort ?? ""}
onChange={handleChange}
/>
</Box>
<Box>
<Typography>{t("settingsEmailUser")}</Typography>
<TextInput
name="systemEmailUser"
placeholder="Leave empty if not required"
value={settingsData?.settings?.systemEmailUser ?? ""}
onChange={handleChange}
/>
</Box>
<Box>
<Typography>{t("settingsEmailAddress")}</Typography>
<TextInput
name="systemEmailAddress"
placeholder="uptime@bluewavelabs.ca"
value={settingsData?.settings?.systemEmailAddress ?? ""}
onChange={handleChange}
/>
</Box>
{(isPasswordSet === false || hasBeenReset === true) && (
<Box>
<Typography>{t("settingsEmailPassword")}</Typography>
<TextInput
name="systemEmailPassword"
type="password"
placeholder="123 456 789 101112"
value={password}
onChange={handlePasswordChange}
endAdornment={<PasswordEndAdornment />}
/>
</Box>
)}
{isPasswordSet === true && hasBeenReset === false && (
<Box>
<Typography>{t("settingsEmailFieldResetLabel")}</Typography>
<Button
onClick={() => {
setPassword("");
setSettingsData({
...settingsData,
settings: { ...settingsData.settings, systemEmailPassword: "" },
});
setHasBeenReset(true);
}}
variant="contained"
color="error"
sx={{ mt: theme.spacing(4) }}
>
{t("reset")}
</Button>
</Box>
)}
</Stack>
</Box>
</ConfigBox>
);
};
SettingsEmail.propTypes = {
settingsData: PropTypes.object,
setSettingsData: PropTypes.func,
handleChange: PropTypes.func,
HEADER_SX: PropTypes.object,
isPasswordSet: PropTypes.bool,
};
export default SettingsEmail;
+17 -11
View File
@@ -11,26 +11,28 @@ import { PropTypes } from "prop-types";
import { useState, useEffect } from "react";
import { useTranslation } from "react-i18next";
const SettingsPagespeed = ({ HEADING_SX, settings, setSettings }) => {
const SettingsPagespeed = ({
HEADING_SX,
settingsData,
setSettingsData,
isApiKeySet,
}) => {
const { t } = useTranslation();
const theme = useTheme();
// Local state
const [apiKey, setApiKey] = useState("");
const [isApiKeySet, setIsApiKeySet] = useState(false);
const [hasBeenReset, setHasBeenReset] = useState(false);
// Handler
const handleChange = (e) => {
setApiKey(e.target.value);
setSettings({ ...settings, pagespeedApiKey: e.target.value });
setSettingsData({
...settingsData,
settings: { ...settingsData.settings, pagespeedApiKey: e.target.value },
});
};
useEffect(() => {
console.log(settings);
setIsApiKeySet(Boolean(settings.pagespeedApiKey) && apiKey === "");
}, [settings, apiKey]);
return (
<ConfigBox>
<Box>
@@ -56,7 +58,10 @@ const SettingsPagespeed = ({ HEADING_SX, settings, setSettings }) => {
<Button
onClick={() => {
setApiKey("");
setSettings({ ...settings, pagespeedApiKey: "" });
setSettingsData({
...settingsData,
settings: { ...settingsData.settings, pagespeedApiKey: "" },
});
setHasBeenReset(true);
}}
variant="contained"
@@ -74,8 +79,9 @@ const SettingsPagespeed = ({ HEADING_SX, settings, setSettings }) => {
SettingsPagespeed.propTypes = {
HEADING_SX: PropTypes.object,
settings: PropTypes.object,
setSettings: PropTypes.func,
settingsData: PropTypes.object,
setSettingsData: PropTypes.func,
isApiKeySet: PropTypes.bool,
};
export default SettingsPagespeed;
+3 -3
View File
@@ -12,7 +12,7 @@ import { PropTypes } from "prop-types";
import { useTranslation } from "react-i18next";
import { useState } from "react";
const SettingsStats = ({ HEADING_SX, handleChange, settings, errors }) => {
const SettingsStats = ({ HEADING_SX, handleChange, settingsData, errors }) => {
const theme = useTheme();
const { t } = useTranslation();
const [isOpen, setIsOpen] = useState(false);
@@ -34,7 +34,7 @@ const SettingsStats = ({ HEADING_SX, handleChange, settings, errors }) => {
name="checkTTL"
label={t("settingsTTLLabel")}
optionalLabel={t("settingsTTLOptionalLabel")}
value={settings?.checkTTL ?? ""}
value={settingsData?.settings?.checkTTL ?? ""}
onChange={handleChange}
type="number"
error={errors.checkTTL ? true : false}
@@ -77,7 +77,7 @@ const SettingsStats = ({ HEADING_SX, handleChange, settings, errors }) => {
SettingsStats.propTypes = {
HEADING_SX: PropTypes.object,
handleChange: PropTypes.func,
settings: PropTypes.object,
settingsData: PropTypes.object,
errors: PropTypes.object,
};
+28 -18
View File
@@ -6,6 +6,7 @@ import SettingsUI from "./SettingsUI";
import SettingsPagespeed from "./SettingsPagespeed";
import SettingsDemoMonitors from "./SettingsDemoMonitors";
import SettingsAbout from "./SettingsAbout";
import SettingsEmail from "./SettingsEmail";
import Button from "@mui/material/Button";
// Utils
import { settingsValidation } from "../../Validation/validation";
@@ -15,7 +16,6 @@ import { useTheme } from "@emotion/react";
import { useTranslation } from "react-i18next";
import { useSelector, useDispatch } from "react-redux";
import { setTimezone, setMode, setLanguage } from "../../Features/UI/uiSlice";
import { getAppSettings } from "../../Features/Settings/settingsSlice";
import SettingsStats from "./SettingsStats";
import {
deleteMonitorChecksByTeamId,
@@ -34,17 +34,14 @@ const Settings = () => {
const { user } = useSelector((state) => state.auth);
// Local state
const [settings, setSettings] = useState({});
const [settingsData, setSettingsData] = useState({});
const [errors, setErrors] = useState({});
// Network
const [isSettingsLoading, settingsError] = useFetchSettings({
settings,
setSettings,
setSettingsData,
});
const [isSaving, saveError, saveSettings] = useSaveSettings();
const [deleteMonitorStats, isDeletingMonitorStats] = UseDeleteMonitorStats();
// Setup
@@ -58,10 +55,15 @@ const Settings = () => {
const { name, value } = e.target;
// Build next state early
const newSettings = { ...settings, [name]: value };
const newSettingsData = {
...settingsData,
settings: { ...settingsData.settings, [name]: value },
};
// Validate
const { error } = settingsValidation.validate(newSettings, { abortEarly: false });
const { error } = settingsValidation.validate(newSettingsData.settings, {
abortEarly: false,
});
if (!error || error.details.length === 0) {
setErrors({});
} else {
@@ -118,11 +120,13 @@ const Settings = () => {
return;
}
setSettings(newSettings);
setSettingsData(newSettingsData);
};
const handleSave = () => {
const { error } = settingsValidation.validate(settings, { abortEarly: false });
const { error } = settingsValidation.validate(settingsData.settings, {
abortEarly: false,
});
if (!error || error.details.length === 0) {
setErrors({});
} else {
@@ -132,7 +136,7 @@ const Settings = () => {
});
setErrors(newErrors);
}
saveSettings(settings);
saveSettings(settingsData?.settings);
};
return (
@@ -152,21 +156,27 @@ const Settings = () => {
/>
<SettingsPagespeed
HEADING_SX={HEADING_SX}
settings={settings}
setSettings={setSettings}
settingsData={settingsData}
setSettingsData={setSettingsData}
isApiKeySet={settingsData?.pagespeedKeySet ?? false}
/>
<SettingsStats
HEADING_SX={HEADING_SX}
settings={settings}
setSettings={setSettings}
settingsData={settingsData}
handleChange={handleChange}
errors={errors}
/>
<SettingsDemoMonitors
isLoading={false}
authIsLoading={false}
checksIsLoading={false}
HEADER_SX={HEADING_SX}
handleChange={handleChange}
isLoading={isSettingsLoading || isSaving || isDeletingMonitorStats}
/>
<SettingsEmail
HEADER_SX={HEADING_SX}
handleChange={handleChange}
settingsData={settingsData}
setSettingsData={setSettingsData}
isPasswordSet={settingsData?.emailPasswordSet ?? false}
/>
<SettingsAbout />
<Stack
+5
View File
@@ -262,6 +262,11 @@ const settingsValidation = joi.object({
}),
pagespeedApiKey: joi.string().allow("").optional(),
language: joi.string().required(),
systemEmailHost: joi.string().allow(""),
systemEmailPort: joi.number().allow(null, ""),
systemEmailAddress: joi.string().allow(""),
systemEmailPassword: joi.string().allow(""),
systemEmailUser: joi.string().allow(""),
});
const dayjsValidator = (value, helpers) => {
+8 -1
View File
@@ -108,6 +108,14 @@
"settingsFailedToAddDemoMonitors": "Failed to add demo monitors",
"settingsMonitorsDeleted": "Successfully deleted all monitors",
"settingsFailedToDeleteMonitors": "Failed to delete all monitors",
"settingsEmail": "Email settings",
"settingsEmailDescription": "Configure email settings",
"settingsEmailHost": "Email host",
"settingsEmailPort": "Email port",
"settingsEmailAddress": "Email address",
"settingsEmailPassword": "Email password",
"settingsEmailUser": "Email user",
"settingsEmailFieldResetLabel": "Password is set. Click Reset to change it.",
"backendUnreachable": "Server Connection Error",
"backendUnreachableMessage": "We're unable to connect to the server. Please check your internet connection or verify your deployment configuration if the problem persists.",
"backendUnreachableError": "Cannot connect to the server. Please try again later.",
@@ -441,4 +449,3 @@
"pageSpeedApiKeyFieldResetLabel": "API key is set. Click Reset to change it.",
"reset": "Reset"
}
+1 -2
View File
@@ -649,9 +649,8 @@ class MonitorController {
sendTestEmail = async (req, res, next) => {
try {
const { to } = req.body;
if (!to || typeof to !== "string") {
return res.error({ msg: this.stringService.errorForValidEmailAddress });
throw new Error(this.stringService.errorForValidEmailAddress);
}
const subject = this.stringService.testEmailSubject;
+15 -2
View File
@@ -13,12 +13,25 @@ class SettingsController {
getAppSettings = async (req, res, next) => {
const dbSettings = await this.settingsService.getDBSettings();
const sanitizedSettings = { ...dbSettings };
const returnSettings = {
pagespeedKeySet: false,
emailPasswordSet: false,
};
if (typeof sanitizedSettings.pagespeedApiKey !== "undefined") {
sanitizedSettings.pagespeedApiKey = "********";
returnSettings.pagespeedKeySet = true;
delete sanitizedSettings.pagespeedApiKey;
}
if (typeof sanitizedSettings.systemEmailPassword !== "undefined") {
returnSettings.emailPasswordSet = true;
delete sanitizedSettings.systemEmailPassword;
}
returnSettings.settings = sanitizedSettings;
return res.success({
msg: this.stringService.getAppSettings,
data: sanitizedSettings,
data: returnSettings,
});
};
+3
View File
@@ -25,6 +25,9 @@ const AppSettingsSchema = mongoose.Schema(
systemEmailPassword: {
type: String,
},
systemEmailUser: {
type: String,
},
singleton: {
type: Boolean,
required: true,
@@ -21,6 +21,11 @@ const updateAppSettings = async (newSettings) => {
delete update.$set.pagespeedApiKey;
}
if (newSettings.systemEmailPassword === "") {
update.$unset = { systemEmailPassword: "" };
delete update.$set.systemEmailPassword;
}
const settings = await AppSettings.findOneAndUpdate({}, update, {
new: true,
upsert: true,
+26 -21
View File
@@ -29,7 +29,10 @@ class EmailService {
this.mjml2html = mjml2html;
this.nodemailer = nodemailer;
this.logger = logger;
this.init();
}
init = async () => {
/**
* Loads an email template from the filesystem.
*
@@ -67,35 +70,15 @@ class EmailService {
serverIsUpTemplate: this.loadTemplate("serverIsUp"),
passwordResetTemplate: this.loadTemplate("passwordReset"),
hardwareIncidentTemplate: this.loadTemplate("hardwareIncident"),
testEmailTemplate: this.loadTemplate("testEmailTemplate")
testEmailTemplate: this.loadTemplate("testEmailTemplate"),
};
/**
* The email transporter used to send emails.
* @type {Object}
*/
const {
systemEmailHost,
systemEmailPort,
systemEmailUser,
systemEmailAddress,
systemEmailPassword,
} = this.settingsService.getSettings();
const emailConfig = {
host: systemEmailHost,
port: systemEmailPort,
secure: true,
auth: {
user: systemEmailUser || systemEmailAddress,
pass: systemEmailPassword,
},
};
this.transporter = this.nodemailer.createTransport(emailConfig);
}
/**
* Asynchronously builds and sends an email using a specified template and context.
*
@@ -106,6 +89,28 @@ class EmailService {
* @returns {Promise<string>} A promise that resolves to the messageId of the sent email.
*/
buildAndSendEmail = async (template, context, to, subject) => {
// TODO - Consider an update transporter method so this only needs to be recreated when smtp settings change
const {
systemEmailHost,
systemEmailPort,
systemEmailUser,
systemEmailAddress,
systemEmailPassword,
} = await this.settingsService.getDBSettings();
const emailConfig = {
host: systemEmailHost,
port: systemEmailPort,
secure: true,
auth: {
user: systemEmailUser || systemEmailAddress,
pass: systemEmailPassword,
},
connectionTimeout: 5000,
};
this.transporter = this.nodemailer.createTransport(emailConfig);
const buildHtml = async (template, context) => {
try {
const mjml = this.templateLookup[template](context);
+1
View File
@@ -431,6 +431,7 @@ const updateAppSettingsBodyValidation = joi.object({
systemEmailPort: joi.number().allow(""),
systemEmailAddress: joi.string().allow(""),
systemEmailPassword: joi.string().allow(""),
systemEmailUser: joi.string().allow(""),
});
//****************************************