- Extracted functions to error.js

- Add validation to advanced settings page
This commit is contained in:
Shemy Gan committed 2024-10-18 11:20:20 -04:00
1 parent 44cee3cefb
commit 8c57f3990b
4 files changed
+339 -279

No files matched your search

+239 -216
View File
@@ -12,45 +12,47 @@ 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(() => {
if (!isAdmin) {
navigate("/");
}
}, [navigate, isAdmin]);
useEffect(() => { const theme = useTheme();
if (!isAdmin) { const { authToken } = useSelector((state) => state.auth);
navigate("/"); const dispatch = useDispatch();
} const settings = useSelector((state) => state.settings);
}, [navigate, isAdmin]); const [localSettings, setLocalSettings] = useState({
apiBaseUrl: "",
logLevel: "debug",
systemEmailHost: "",
systemEmailPort: "",
systemEmailAddress: "",
systemEmailPassword: "",
jwtTTL: "",
dbType: "",
redisHost: "",
redisPort: "",
pagespeedApiKey: "",
});
const [errors, setErrors] = useState({});
const theme = useTheme(); useEffect(() => {
const { authToken } = useSelector((state) => state.auth); const getSettings = async () => {
const dispatch = useDispatch(); const action = await dispatch(getAppSettings({ authToken }));
const settings = useSelector((state) => state.settings); if (action.payload?.success) {
const [localSettings, setLocalSettings] = useState({ setLocalSettings(action.payload.data);
apiBaseUrl: "", } else {
logLevel: "debug", createToast({ body: "Failed to get settings" });
systemEmailHost: "", }
systemEmailPort: "", };
systemEmailAddress: "", getSettings();
systemEmailPassword: "", }, [authToken, dispatch]);
jwtTTL: "",
dbType: "",
redisHost: "",
redisPort: "",
pagespeedApiKey: "",
});
useEffect(() => {
const getSettings = async () => {
const action = await dispatch(getAppSettings({ authToken }));
if (action.payload.success) {
setLocalSettings(action.payload.data);
} else {
createToast({ body: "Failed to get settings" });
}
};
getSettings();
}, [authToken, dispatch]);
const logItems = [ const logItems = [
{ _id: 1, name: "none" }, { _id: 1, name: "none" },
@@ -72,189 +74,210 @@ const AdvancedSettings = ({ isAdmin }) => {
setLocalSettings({ ...localSettings, logLevel: newLogLevel }); setLocalSettings({ ...localSettings, logLevel: newLogLevel });
}; };
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 () => {
const action = await dispatch( if (hasValidationErrors(localSettings, advancedSettingsValidation, setErrors))
updateAppSettings({ settings: localSettings, authToken }) return;
); const action = await dispatch(
let body = ""; updateAppSettings({ settings: localSettings, authToken })
if (action.payload.success) { );
console.log(action.payload.data); let body = "";
setLocalSettings(action.payload.data); if (action.payload.success) {
body = "Settings saved successfully"; console.log(action.payload.data);
} else { setLocalSettings(action.payload.data);
body = "Failed to save settings"; body = "Settings saved successfully";
} } else {
createToast({ body }); body = "Failed to save settings";
}; }
createToast({ body });
};
return ( return (
<Box <Box
className="settings" className="settings"
style={{ style={{
paddingBottom: 0, paddingBottom: 0,
}} }}
> >
<Stack <Stack
component="form" component="form"
gap={theme.spacing(12)} gap={theme.spacing(12)}
noValidate noValidate
spellCheck="false" spellCheck="false"
> >
<ConfigBox> <ConfigBox>
<Box> <Box>
<Typography component="h1">Client settings</Typography> <Typography component="h1">Client settings</Typography>
<Typography sx={{ mt: theme.spacing(2) }}> <Typography sx={{ mt: theme.spacing(2) }}>
Modify client settings here. Modify client settings here.
</Typography> </Typography>
</Box> </Box>
<Stack gap={theme.spacing(20)}> <Stack gap={theme.spacing(20)}>
<Field <Field
id="apiBaseUrl" id="apiBaseUrl"
label="API URL Host" label="API URL Host"
value={localSettings.apiBaseUrl} value={localSettings.apiBaseUrl}
onChange={handleChange} onChange={handleChange}
/> error={errors.apiBaseUrl}
<Select />
id="logLevel" <Select
label="Log level" id="logLevel"
name="logLevel" label="Log level"
items={logItems} name="logLevel"
value={logItemLookup[localSettings.logLevel]} items={logItems}
onChange={handleLogLevel} value={logItemLookup[localSettings.logLevel]}
/> onChange={handleLogLevel}
</Stack> error={errors.logLevel}
</ConfigBox> />
<ConfigBox> </Stack>
<Box> </ConfigBox>
<Typography component="h1">Email settings</Typography> <ConfigBox>
<Typography sx={{ mt: theme.spacing(2) }}> <Box>
Set your host email settings here. These settings are used for sending <Typography component="h1">Email settings</Typography>
system emails. <Typography sx={{ mt: theme.spacing(2) }}>
</Typography> Set your host email settings here. These settings are used for
</Box> sending system emails.
<Stack gap={theme.spacing(20)}> </Typography>
<Field </Box>
type="text" <Stack gap={theme.spacing(20)}>
id="systemEmailHost" <Field
label="Email host" type="text"
name="systemEmailHost" id="systemEmailHost"
value={localSettings.systemEmailHost} label="Email host"
onChange={handleChange} name="systemEmailHost"
/> value={localSettings.systemEmailHost}
<Field onChange={handleChange}
type="number" error={errors.systemEmailHost}
id="systemEmailPort" />
label="System email address" <Field
name="systemEmailPort" type="number"
value={localSettings.systemEmailPort.toString()} id="systemEmailPort"
onChange={handleChange} label="System email address"
/> name="systemEmailPort"
<Field value={localSettings.systemEmailPort.toString()}
type="email" onChange={handleChange}
id="systemEmailAddress" error={errors.systemEmailPort}
label="System email address" />
name="systemEmailAddress" <Field
value={localSettings.systemEmailAddress} type="email"
onChange={handleChange} id="systemEmailAddress"
/> label="System email address"
<Field name="systemEmailAddress"
type="text" value={localSettings.systemEmailAddress}
id="systemEmailPassword" onChange={handleChange}
label="System email password" error={errors.systemEmailAddress}
name="systemEmailPassword" />
value={localSettings.systemEmailPassword} <Field
onChange={handleChange} type="text"
/> id="systemEmailPassword"
</Stack> label="System email password"
</ConfigBox> name="systemEmailPassword"
<ConfigBox> value={localSettings.systemEmailPassword}
<Box> onChange={handleChange}
<Typography component="h1">Server settings</Typography> error={errors.systemEmailPassword}
<Typography sx={{ mt: theme.spacing(2) }}> />
Modify server settings here. </Stack>
</Typography> </ConfigBox>
</Box> <ConfigBox>
<Stack gap={theme.spacing(20)}> <Box>
<Field <Typography component="h1">Server settings</Typography>
type="text" <Typography sx={{ mt: theme.spacing(2) }}>
id="jwtTTL" Modify server settings here.
label="JWT time to live" </Typography>
name="jwtTTL" </Box>
value={localSettings.jwtTTL} <Stack gap={theme.spacing(20)}>
onChange={handleChange} <Field
/> type="text"
<Field id="jwtTTL"
type="text" label="JWT time to live"
id="dbType" name="jwtTTL"
label="Database type" value={localSettings.jwtTTL}
name="dbType" onChange={handleChange}
value={localSettings.dbType} error={errors.jwtTTL}
onChange={handleChange} />
/> <Field
<Field type="text"
type="text" id="dbType"
id="redisHost" label="Database type"
label="Redis host" name="dbType"
name="redisHost" value={localSettings.dbType}
value={localSettings.redisHost} onChange={handleChange}
onChange={handleChange} error={errors.dbType}
/> />
<Field <Field
type="number" type="text"
id="redisPort" id="redisHost"
label="Redis port" label="Redis host"
name="redisPort" name="redisHost"
value={localSettings.redisPort.toString()} value={localSettings.redisHost}
onChange={handleChange} onChange={handleChange}
/> error={errors.redisHost}
<Field />
type="text" <Field
id="pagespeedApiKey" type="number"
label="PageSpeed API key" id="redisPort"
name="pagespeedApiKey" label="Redis port"
value={localSettings.pagespeedApiKey} name="redisPort"
onChange={handleChange} value={localSettings.redisPort.toString()}
/> onChange={handleChange}
</Stack> error={errors.redisPort}
</ConfigBox> />
<ConfigBox> <Field
<Box> type="text"
<Typography component="h1">About</Typography> id="pagespeedApiKey"
</Box> label="PageSpeed API key"
<Box> name="pagespeedApiKey"
<Typography component="h2">BlueWave Uptime v1.0.0</Typography> value={localSettings.pagespeedApiKey}
<Typography sx={{ mt: theme.spacing(2), mb: theme.spacing(6), opacity: 0.6 }}> onChange={handleChange}
Developed by Bluewave Labs. error={errors.pagespeedApiKey}
</Typography> />
<Link </Stack>
level="secondary" </ConfigBox>
url="https://github.com/bluewave-labs" <ConfigBox>
label="https://github.com/bluewave-labs" <Box>
/> <Typography component="h1">About</Typography>
</Box> </Box>
</ConfigBox> <Box>
<Stack <Typography component="h2">BlueWave Uptime v1.0.0</Typography>
direction="row" <Typography
justifyContent="flex-end" sx={{ mt: theme.spacing(2), mb: theme.spacing(6), opacity: 0.6 }}
> >
<LoadingButton Developed by Bluewave Labs.
loading={settings.isLoading || settings.authIsLoading} </Typography>
variant="contained" <Link
color="primary" level="secondary"
sx={{ px: theme.spacing(12), mt: theme.spacing(20) }} url="https://github.com/bluewave-labs"
onClick={handleSave} label="https://github.com/bluewave-labs"
> />
Save </Box>
</LoadingButton> </ConfigBox>
</Stack> <Stack direction="row" justifyContent="flex-end">
</Stack> <LoadingButton
</Box> loading={settings.isLoading || settings.authIsLoading}
); variant="contained"
color="primary"
sx={{ px: theme.spacing(12), mt: theme.spacing(20) }}
onClick={handleSave}
>
Save
</LoadingButton>
</Stack>
</Stack>
</Box>
);
}; };
AdvancedSettings.propTypes = { AdvancedSettings.propTypes = {
@@ -28,6 +28,7 @@ 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) {
@@ -145,46 +146,36 @@ const CreateMaintenance = () => {
return; return;
} }
const res = await networkService.getMaintenanceWindowById({ const res = await networkService.getMaintenanceWindowById({
authToken: authToken, authToken: authToken,
maintenanceWindowId: maintenanceWindowId, maintenanceWindowId: maintenanceWindowId,
}); });
const maintenanceWindow = res.data.data; const maintenanceWindow = res.data.data;
const { name, start, end, repeat, monitorId } = maintenanceWindow; const { name, start, end, repeat, monitorId } = maintenanceWindow;
const startTime = dayjs(start); const startTime = dayjs(start);
const endTime = dayjs(end); const endTime = dayjs(end);
const durationInMs = endTime.diff(startTime, "milliseconds").toString(); const durationInMs = endTime.diff(startTime, "milliseconds").toString();
const { duration, durationUnit } = getDurationAndUnit(durationInMs); const { duration, durationUnit } = getDurationAndUnit(durationInMs);
const monitor = monitors.find((monitor) => monitor._id === monitorId); const monitor = monitors.find((monitor) => monitor._id === monitorId);
setForm({ setForm({
...form, ...form,
name, name,
repeat: REVERSE_REPEAT_LOOKUP[repeat], repeat: REVERSE_REPEAT_LOOKUP[repeat],
startDate: startTime, startDate: startTime,
startTime, startTime,
duration, duration,
durationUnit, durationUnit,
monitors: monitor ? [monitor] : [], monitors: monitor ? [monitor] : [],
}); });
} catch (error) { } catch (error) {
createToast({ body: "Failed to fetch data" }); createToast({ body: "Failed to fetch data" });
logger.error("Failed to fetch monitors", error); logger.error("Failed to fetch monitors", error);
} finally { } finally {
setIsLoading(false); setIsLoading(false);
} }
}; };
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);
@@ -223,29 +214,17 @@ const CreateMaintenance = () => {
}); });
}; };
const handleSubmit = async () => { const handleSubmit = async () => {
const { error } = maintenanceWindowValidation.validate(form, { if(hasValidationErrors(form, maintenanceWindowValidation, setErrors))
abortEarly: false, return;
}); // Build timestamp for maintenance window from startDate and startTime
const start = dayjs(form.startDate)
// If errors, return early .set("hour", form.startTime.hour())
if (error) { .set("minute", form.startTime.minute());
const newErrors = {}; // Build end timestamp for maintenance window
error.details.forEach((err) => { const MS_MULTIPLIER = MS_LOOKUP[form.durationUnit];
newErrors[err.path[0]] = err.message; const durationInMs = form.duration * MS_MULTIPLIER;
}); const end = start.add(durationInMs);
setErrors(newErrors);
logger.error(error);
return;
}
// Build timestamp for maintenance window from startDate and startTime
const start = dayjs(form.startDate)
.set("hour", form.startTime.hour())
.set("minute", form.startTime.minute());
// Build end timestamp for maintenance window
const MS_MULTIPLIER = MS_LOOKUP[form.durationUnit];
const durationInMs = form.duration * MS_MULTIPLIER;
const end = start.add(durationInMs);
// Get repeat value in milliseconds // Get repeat value in milliseconds
const repeat = REPEAT_LOOKUP[form.repeat]; const repeat = REPEAT_LOOKUP[form.repeat];
+25
View File
@@ -0,0 +1,25 @@
const buildErrors = (prev, id, error) => {
const updatedErrors = { ...prev };
if (error) {
updatedErrors[id] = error.details[0].message;
} 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;
});
setErrors(newErrors);
return true;
}
return false;
};
export { buildErrors, hasValidationErrors };
+33
View File
@@ -128,10 +128,43 @@ 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(),
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,
}; };