diff --git a/Client/src/Components/Inputs/Field/index.jsx b/Client/src/Components/Inputs/Field/index.jsx index 1b5ab0c7c..dfcdb5920 100644 --- a/Client/src/Components/Inputs/Field/index.jsx +++ b/Client/src/Components/Inputs/Field/index.jsx @@ -41,6 +41,7 @@ const Field = forwardRef( placeholder, value, onChange, + onBlur, onInput, error, disabled, @@ -115,6 +116,7 @@ const Field = forwardRef( value={value} onInput={onInput} onChange={onChange} + onBlur={onBlur} disabled={disabled} inputRef={ref} inputProps={{ @@ -216,6 +218,7 @@ Field.propTypes = { placeholder: PropTypes.string, value: PropTypes.string.isRequired, onChange: PropTypes.func, + onBlur: PropTypes.func, onInput: PropTypes.func, error: PropTypes.string, disabled: PropTypes.bool, diff --git a/Client/src/Components/Inputs/Select/index.jsx b/Client/src/Components/Inputs/Select/index.jsx index e470881ec..8517c3214 100644 --- a/Client/src/Components/Inputs/Select/index.jsx +++ b/Client/src/Components/Inputs/Select/index.jsx @@ -46,6 +46,7 @@ const Select = ({ value, items, onChange, + onBlur, sx, name = "", }) => { @@ -76,6 +77,7 @@ const Select = ({ className="select-component" value={value} onChange={onChange} + onBlur={onBlur} displayEmpty name={name} inputProps={{ id: id }} @@ -140,6 +142,7 @@ Select.propTypes = { }) ).isRequired, onChange: PropTypes.func.isRequired, + onBlur: PropTypes.func, sx: PropTypes.object, }; diff --git a/Client/src/Pages/AdvancedSettings/index.jsx b/Client/src/Pages/AdvancedSettings/index.jsx index ce1c89250..a830159b8 100644 --- a/Client/src/Pages/AdvancedSettings/index.jsx +++ b/Client/src/Pages/AdvancedSettings/index.jsx @@ -12,6 +12,8 @@ import { useNavigate } from "react-router"; import { getAppSettings, updateAppSettings } from "../../Features/Settings/settingsSlice"; import { useState, useEffect } from "react"; import Select from "../../Components/Inputs/Select"; +import { advancedSettingsValidation } from "../../Validation/validation"; +import { buildErrors, hasValidationErrors } from "../../Validation/error"; const AdvancedSettings = ({ isAdmin }) => { const navigate = useNavigate(); @@ -21,7 +23,7 @@ const AdvancedSettings = ({ isAdmin }) => { navigate("/"); } }, [navigate, isAdmin]); - + const [errors, setErrors] = useState({}); const theme = useTheme(); const { authToken } = useSelector((state) => state.auth); const dispatch = useDispatch(); @@ -33,17 +35,30 @@ const AdvancedSettings = ({ isAdmin }) => { systemEmailPort: "", systemEmailAddress: "", systemEmailPassword: "", - jwtTTL: "", + jwtTTLNum: 99, + jwtTTLUnits: "days", + jwtTTL: "99d", dbType: "", redisHost: "", redisPort: "", pagespeedApiKey: "", }); + const parseJWTTTL = (data) => { + if (data.jwtTTL) { + const len = data.jwtTTL.length; + data.jwtTTLNum = data.jwtTTL.substring(0, len - 1); + data.jwtTTLUnits = unitItems.filter( + (itm) => itm._id == data.jwtTTL.substring(len - 1) + )[0].name; + } + }; + useEffect(() => { const getSettings = async () => { const action = await dispatch(getAppSettings({ authToken })); if (action.payload.success) { + parseJWTTTL(action.payload.data); setLocalSettings(action.payload.data); } else { createToast({ body: "Failed to get settings" }); @@ -66,24 +81,56 @@ const AdvancedSettings = ({ isAdmin }) => { warn: 4, }; + const unitItemLookup = { + days: "d", + hours: "h", + }; + const unitItems = Object.keys(unitItemLookup).map((key) => ({ + _id: unitItemLookup[key], + name: key, + })); + const handleLogLevel = (e) => { const id = e.target.value; const newLogLevel = logItems.find((item) => item._id === id).name; setLocalSettings({ ...localSettings, logLevel: newLogLevel }); }; + const handleJWTTTLUnits = (e) => { + const id = e.target.value; + const newUnits = unitItems.find((item) => item._id === id).name; + setLocalSettings({ ...localSettings, jwtTTLUnits: newUnits }); + }; + + const handleBlur = (event) => { + const { value, id } = event.target; + const { error } = advancedSettingsValidation.validate( + { [id]: value }, + { + abortEarly: false, + } + ); + setErrors((prev) => { + return buildErrors(prev, id, error); + }); + }; const handleChange = (event) => { const { value, id } = event.target; setLocalSettings({ ...localSettings, [id]: value }); }; const handleSave = async () => { + localSettings.jwtTTL = + localSettings.jwtTTLNum + unitItemLookup[localSettings.jwtTTLUnits]; + if (hasValidationErrors(localSettings, advancedSettingsValidation, setErrors)) { + return; + } const action = await dispatch( updateAppSettings({ settings: localSettings, authToken }) ); let body = ""; if (action.payload.success) { - console.log(action.payload.data); + parseJWTTTL(action.payload.data); setLocalSettings(action.payload.data); body = "Settings saved successfully"; } else { @@ -118,6 +165,8 @@ const AdvancedSettings = ({ isAdmin }) => { label="API URL Host" value={localSettings.apiBaseUrl} onChange={handleChange} + onBlur={handleBlur} + error={errors.apiBaseUrl} /> + { name="dbType" value={localSettings.dbType} onChange={handleChange} + onBlur={handleBlur} + error={errors.dbType} /> { name="redisHost" value={localSettings.redisHost} onChange={handleChange} + onBlur={handleBlur} + error={errors.redisHost} /> { name="pagespeedApiKey" value={localSettings.pagespeedApiKey} onChange={handleChange} + onBlur={handleBlur} + error={errors.pagespeedApiKey} /> diff --git a/Client/src/Pages/Maintenance/CreateMaintenance/index.jsx b/Client/src/Pages/Maintenance/CreateMaintenance/index.jsx index 4dbf8f747..310587442 100644 --- a/Client/src/Pages/Maintenance/CreateMaintenance/index.jsx +++ b/Client/src/Pages/Maintenance/CreateMaintenance/index.jsx @@ -28,6 +28,7 @@ import { MS_PER_WEEK, } from "../../../Utils/timeUtils"; import { useNavigate, useParams } from "react-router-dom"; +import { buildErrors, hasValidationErrors } from "../../../Validation/error"; const getDurationAndUnit = (durationInMs) => { if (durationInMs % MS_PER_DAY === 0) { @@ -176,16 +177,6 @@ const CreateMaintenance = () => { fetchMonitors(); }, [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) => { setSearch(value); }; @@ -224,20 +215,8 @@ const CreateMaintenance = () => { }; const handleSubmit = async () => { - const { error } = maintenanceWindowValidation.validate(form, { - abortEarly: false, - }); - - // If errors, return early - if (error) { - const newErrors = {}; - error.details.forEach((err) => { - newErrors[err.path[0]] = err.message; - }); - setErrors(newErrors); - logger.error(error); - return; - } + if (hasValidationErrors(form, maintenanceWindowValidation, setErrors)) + return; // Build timestamp for maintenance window from startDate and startTime const start = dayjs(form.startDate) .set("hour", form.startTime.hour()) diff --git a/Client/src/Validation/error.js b/Client/src/Validation/error.js new file mode 100644 index 000000000..a616e13f5 --- /dev/null +++ b/Client/src/Validation/error.js @@ -0,0 +1,37 @@ +const buildErrors = (prev, id, error) => { + const updatedErrors = { ...prev }; + if (error) { + updatedErrors[id] = error.details[0].message?? "Validation error"; + } else { + delete updatedErrors[id]; + } + return updatedErrors; +}; + +const hasValidationErrors = (form, validation, setErrors) => { + const { error } = validation.validate(form, { + abortEarly: false, + }); + if (error) { + const newErrors = {}; + error.details.forEach((err) => { + if ( + ![ + "clientHost", + "refreshTokenSecret", + "dbConnectionString", + "refreshTokenTTL", + "jwtTTL", + ].includes(err.path[0]) + ) { + newErrors[err.path[0]] = err.message ?? "Validation error"; + } + }); + if (Object.keys(newErrors).length > 0) { + setErrors(newErrors); + return true; + } else return false; + } + return false; +}; +export { buildErrors, hasValidationErrors }; \ No newline at end of file diff --git a/Client/src/Validation/validation.js b/Client/src/Validation/validation.js index c620bdf43..08b1632c3 100644 --- a/Client/src/Validation/validation.js +++ b/Client/src/Validation/validation.js @@ -128,10 +128,43 @@ const maintenanceWindowValidation = joi.object({ monitors: joi.array().min(1), }); +const advancedSettingsValidation = joi.object({ + apiBaseUrl: joi.string().uri({ allowRelative: true }).trim().messages({ + "string.empty": "API base url is required.", + "string.uri": "The URL you provided is not valid.", + }), + logLevel: joi.string().valid("debug", "none", "error", "warn").allow(""), + systemEmailHost: joi.string().allow(""), + systemEmailPort: joi.number().allow(null, ""), + systemEmailAddress: joi.string().allow(""), + systemEmailPassword: joi.string().allow(""), + jwtTTLNum: joi.number().messages({ + "number.base": "JWT TTL is required.", + }), + jwtTTLUnits: joi + .string() + .trim() + .custom((value, helpers) => { + if (!["days", "hours"].includes(value)) { + return helpers.message("JWT TTL unit is required."); + } + return value; + }), + dbType: joi.string().trim().messages({ + "string.empty": "DB type is required.", + }), + redisHost: joi.string().trim().messages({ + "string.empty": "Redis host is required.", + }), + redisPort: joi.number().allow(null, ""), + pagespeedApiKey: joi.string().allow(""), +}); + export { credentials, imageValidation, monitorValidation, settingsValidation, maintenanceWindowValidation, + advancedSettingsValidation }; diff --git a/guides/users-guide/server-settings.md b/guides/users-guide/server-settings.md index 6276f3c42..ae1380dff 100644 --- a/guides/users-guide/server-settings.md +++ b/guides/users-guide/server-settings.md @@ -26,10 +26,12 @@ Here you can setup the following: **Email settings:** Set your host email settings here. These settings are used for sending system emails. -Server settings: Several server settings can be done here. Alternatively, you can add a pagespeed API key to bypass Google's limitations (albeit they are generous about it) +**Server settings:** Several server settings can be done here. Alternatively, you can add a pagespeed API key to bypass Google's limitations (albeit they are generous about it) + +Select a number for jwt TTL and a unit for it (days or hours), the combined result +would be in vercel/ms time format, e.g "99d", this will be sent to server to persist -\