Merge: Fix #1587 UI + dns: new settings for cache

* commit '7dd3d944e86808412b82d7e0d804ef1909443e81':
  Extract validation functions in the separate file
  Add DNS cache setting UI
  + dns: new settings for cache
This commit is contained in:
Andrey Meshkov 2020-07-06 01:37:39 +03:00
commit 2f76f5d048
17 changed files with 448 additions and 195 deletions

View File

@ -223,6 +223,8 @@
"anonymize_client_ip": "Anonymize client IP", "anonymize_client_ip": "Anonymize client IP",
"anonymize_client_ip_desc": "Don't save the full IP address of the client in logs and statistics", "anonymize_client_ip_desc": "Don't save the full IP address of the client in logs and statistics",
"dns_config": "DNS server configuration", "dns_config": "DNS server configuration",
"dns_cache_config": "DNS cache configuration",
"dns_cache_config_desc": "Here you can configure DNS cache",
"blocking_mode": "Blocking mode", "blocking_mode": "Blocking mode",
"default": "Default", "default": "Default",
"nxdomain": "NXDOMAIN", "nxdomain": "NXDOMAIN",
@ -529,5 +531,17 @@
"rewritten": "Rewritten", "rewritten": "Rewritten",
"safe_search": "Safe search", "safe_search": "Safe search",
"blocklist": "Blocklist", "blocklist": "Blocklist",
"milliseconds_abbreviation": "ms" "milliseconds_abbreviation": "ms",
"dnssec_enable_desc": "Set DNSSEC flag in the outcoming DNS queries and check the result (DNSSEC-enabled resolver is required)",
"cache_size": "Cache size",
"cache_size_desc": "DNS cache size (in bytes)",
"cache_ttl_min_override": "Override minimum TTL",
"cache_ttl_max_override": "Override maximum TTL",
"enter_cache_size": "Enter cache size",
"enter_cache_ttl_min_override": "Enter minimum TTL",
"enter_cache_ttl_max_override": "Enter maximum TTL",
"cache_ttl_min_override_desc": "Override TTL value (minimum) received from upstream server. This value can't larger than 3600 (1 hour)",
"cache_ttl_max_override_desc": "Override TTL value (maximum) received from upstream server",
"min_exceeds_max_value": "Minimum value exceeds maximum value",
"value_not_larger_than": "Value can't be larger than {{maximum}}"
} }

View File

@ -3,8 +3,8 @@ import PropTypes from 'prop-types';
import { Field, reduxForm } from 'redux-form'; import { Field, reduxForm } from 'redux-form';
import { Trans, withTranslation } from 'react-i18next'; import { Trans, withTranslation } from 'react-i18next';
import flow from 'lodash/flow'; import flow from 'lodash/flow';
import { renderInputField } from '../../helpers/form';
import { renderInputField, required, isValidPath } from '../../helpers/form'; import { validatePath, validateRequiredValue } from '../../helpers/validators';
import { FORM_NAME } from '../../helpers/constants'; import { FORM_NAME } from '../../helpers/constants';
const Form = (props) => { const Form = (props) => {
@ -28,7 +28,7 @@ const Form = (props) => {
component={renderInputField} component={renderInputField}
className="form-control" className="form-control"
placeholder={t('enter_name_hint')} placeholder={t('enter_name_hint')}
validate={[required]} validate={[validateRequiredValue]}
normalizeOnBlur={(data) => data.trim()} normalizeOnBlur={(data) => data.trim()}
/> />
</div> </div>
@ -40,7 +40,7 @@ const Form = (props) => {
component={renderInputField} component={renderInputField}
className="form-control" className="form-control"
placeholder={t('enter_url_or_path_hint')} placeholder={t('enter_url_or_path_hint')}
validate={[required, isValidPath]} validate={[validateRequiredValue, validatePath]}
normalizeOnBlur={(data) => data.trim()} normalizeOnBlur={(data) => data.trim()}
/> />
</div> </div>

View File

@ -3,10 +3,8 @@ import PropTypes from 'prop-types';
import { Field, reduxForm } from 'redux-form'; import { Field, reduxForm } from 'redux-form';
import { Trans, withTranslation } from 'react-i18next'; import { Trans, withTranslation } from 'react-i18next';
import flow from 'lodash/flow'; import flow from 'lodash/flow';
import { renderInputField } from '../../../helpers/form';
import { import { validateAnswer, validateDomain, validateRequiredValue } from '../../../helpers/validators';
renderInputField, required, domain, answer,
} from '../../../helpers/form';
import { FORM_NAME } from '../../../helpers/constants'; import { FORM_NAME } from '../../../helpers/constants';
const Form = (props) => { const Form = (props) => {
@ -34,7 +32,7 @@ const Form = (props) => {
type="text" type="text"
className="form-control" className="form-control"
placeholder={t('form_domain')} placeholder={t('form_domain')}
validate={[required, domain]} validate={[validateRequiredValue, validateDomain]}
/> />
</div> </div>
@ -61,7 +59,7 @@ const Form = (props) => {
type="text" type="text"
className="form-control" className="form-control"
placeholder={t('form_answer')} placeholder={t('form_answer')}
validate={[required, answer]} validate={[validateRequiredValue, validateAnswer]}
/> />
</div> </div>
</div> </div>

View File

@ -13,13 +13,12 @@ import Tabs from '../../ui/Tabs';
import Examples from '../Dns/Upstream/Examples'; import Examples from '../Dns/Upstream/Examples';
import { toggleAllServices } from '../../../helpers/helpers'; import { toggleAllServices } from '../../../helpers/helpers';
import { import {
required,
clientId,
renderInputField, renderInputField,
renderGroupField, renderGroupField,
renderSelectField, renderSelectField,
renderServiceField, renderServiceField,
} from '../../../helpers/form'; } from '../../../helpers/form';
import { validateClientId, validateRequiredValue } from '../../../helpers/validators';
import { FORM_NAME, SERVICES } from '../../../helpers/constants'; import { FORM_NAME, SERVICES } from '../../../helpers/constants';
import './Service.css'; import './Service.css';
@ -48,12 +47,12 @@ const settingsCheckboxes = [
const validate = (values) => { const validate = (values) => {
const errors = {}; const errors = {};
const { name, ids } = values; const { name, ids } = values;
errors.name = required(name); errors.name = validateRequiredValue(name);
if (ids && ids.length) { if (ids && ids.length) {
const idArrayErrors = []; const idArrayErrors = [];
ids.forEach((id, idx) => { ids.forEach((id, idx) => {
idArrayErrors[idx] = required(id) || clientId(id); idArrayErrors[idx] = validateRequiredValue(id) || validateClientId(id);
}); });
if (idArrayErrors.length) { if (idArrayErrors.length) {

View File

@ -4,11 +4,9 @@ import PropTypes from 'prop-types';
import { Field, reduxForm, formValueSelector } from 'redux-form'; import { Field, reduxForm, formValueSelector } from 'redux-form';
import { Trans, withTranslation } from 'react-i18next'; import { Trans, withTranslation } from 'react-i18next';
import flow from 'lodash/flow'; import flow from 'lodash/flow';
import { renderInputField, toNumber } from '../../../helpers/form';
import {
renderInputField, required, ipv4, isPositive, toNumber,
} from '../../../helpers/form';
import { FORM_NAME } from '../../../helpers/constants'; import { FORM_NAME } from '../../../helpers/constants';
import { validateIpv4, validateIsPositiveValue, validateRequiredValue } from '../../../helpers/validators';
const renderInterfaces = ((interfaces) => ( const renderInterfaces = ((interfaces) => (
Object.keys(interfaces).map((item) => { Object.keys(interfaces).map((item) => {
@ -96,7 +94,7 @@ let Form = (props) => {
name="interface_name" name="interface_name"
component="select" component="select"
className="form-control custom-select" className="form-control custom-select"
validate={[required]} validate={[validateRequiredValue]}
> >
<option value="" disabled={enabled}> <option value="" disabled={enabled}>
{t('dhcp_interface_select')} {t('dhcp_interface_select')}
@ -125,7 +123,7 @@ let Form = (props) => {
type="text" type="text"
className="form-control" className="form-control"
placeholder={t('dhcp_form_gateway_input')} placeholder={t('dhcp_form_gateway_input')}
validate={[ipv4, required]} validate={[validateIpv4, validateRequiredValue]}
/> />
</div> </div>
<div className="form__group form__group--settings"> <div className="form__group form__group--settings">
@ -137,7 +135,7 @@ let Form = (props) => {
type="text" type="text"
className="form-control" className="form-control"
placeholder={t('dhcp_form_subnet_input')} placeholder={t('dhcp_form_subnet_input')}
validate={[ipv4, required]} validate={[validateIpv4, validateRequiredValue]}
/> />
</div> </div>
</div> </div>
@ -155,7 +153,7 @@ let Form = (props) => {
type="text" type="text"
className="form-control" className="form-control"
placeholder={t('dhcp_form_range_start')} placeholder={t('dhcp_form_range_start')}
validate={[ipv4, required]} validate={[validateIpv4, validateRequiredValue]}
/> />
</div> </div>
<div className="col"> <div className="col">
@ -166,7 +164,7 @@ let Form = (props) => {
type="text" type="text"
className="form-control" className="form-control"
placeholder={t('dhcp_form_range_end')} placeholder={t('dhcp_form_range_end')}
validate={[ipv4, required]} validate={[validateIpv4, validateRequiredValue]}
/> />
</div> </div>
</div> </div>
@ -179,7 +177,7 @@ let Form = (props) => {
type="number" type="number"
className="form-control" className="form-control"
placeholder={t('dhcp_form_lease_input')} placeholder={t('dhcp_form_lease_input')}
validate={[required, isPositive]} validate={[validateRequiredValue, validateIsPositiveValue]}
normalize={toNumber} normalize={toNumber}
/> />
</div> </div>

View File

@ -3,10 +3,8 @@ import PropTypes from 'prop-types';
import { Field, reduxForm } from 'redux-form'; import { Field, reduxForm } from 'redux-form';
import { Trans, withTranslation } from 'react-i18next'; import { Trans, withTranslation } from 'react-i18next';
import flow from 'lodash/flow'; import flow from 'lodash/flow';
import { renderInputField } from '../../../../helpers/form';
import { import { validateIpv4, validateMac, validateRequiredValue } from '../../../../helpers/validators';
renderInputField, ipv4, mac, required,
} from '../../../../helpers/form';
import { FORM_NAME } from '../../../../helpers/constants'; import { FORM_NAME } from '../../../../helpers/constants';
const Form = (props) => { const Form = (props) => {
@ -31,7 +29,7 @@ const Form = (props) => {
type="text" type="text"
className="form-control" className="form-control"
placeholder={t('form_enter_mac')} placeholder={t('form_enter_mac')}
validate={[required, mac]} validate={[validateRequiredValue, validateMac]}
/> />
</div> </div>
<div className="form__group"> <div className="form__group">
@ -42,7 +40,7 @@ const Form = (props) => {
type="text" type="text"
className="form-control" className="form-control"
placeholder={t('form_enter_ip')} placeholder={t('form_enter_ip')}
validate={[required, ipv4]} validate={[validateRequiredValue, validateIpv4]}
/> />
</div> </div>
<div className="form__group"> <div className="form__group">

View File

@ -0,0 +1,95 @@
import React from 'react';
import PropTypes from 'prop-types';
import { Field, reduxForm } from 'redux-form';
import { Trans, useTranslation } from 'react-i18next';
import { shallowEqual, useSelector } from 'react-redux';
import { renderInputField, toNumber } from '../../../../helpers/form';
import { validateBiggerOrEqualZeroValue, getMaxValueValidator, validateRequiredValue } from '../../../../helpers/validators';
import { FORM_NAME, SECONDS_IN_HOUR } from '../../../../helpers/constants';
const validateMaxValue3600 = getMaxValueValidator(SECONDS_IN_HOUR);
const getInputFields = ({ validateRequiredValue, validateMaxValue3600 }) => [{
name: 'cache_size',
title: 'cache_size',
description: 'cache_size_desc',
placeholder: 'enter_cache_size',
validate: validateRequiredValue,
},
{
name: 'cache_ttl_min',
title: 'cache_ttl_min_override',
description: 'cache_ttl_min_override_desc',
placeholder: 'enter_cache_ttl_min_override',
max: SECONDS_IN_HOUR,
validate: validateMaxValue3600,
},
{
name: 'cache_ttl_max',
title: 'cache_ttl_max_override',
description: 'cache_ttl_max_override_desc',
placeholder: 'enter_cache_ttl_max_override',
}];
const Form = ({
handleSubmit, submitting, invalid,
}) => {
const { t } = useTranslation();
const { processingSetConfig } = useSelector((state) => state.dnsConfig, shallowEqual);
const {
cache_ttl_max, cache_ttl_min,
} = useSelector((state) => state.form[FORM_NAME.CACHE].values, shallowEqual);
const minExceedsMax = cache_ttl_min > cache_ttl_max;
const INPUTS_FIELDS = getInputFields({
validateRequiredValue,
validateMaxValue3600,
});
return <form onSubmit={handleSubmit}>
<div className="row">
{INPUTS_FIELDS.map(({
name, title, description, placeholder, validate, max,
}) => <div className="col-12" key={name}>
<div className="col-7 p-0">
<div className="form__group form__group--settings">
<label htmlFor={name}
className="form__label form__label--with-desc">{t(title)}</label>
<div className="form__desc form__desc--top">{t(description)}</div>
<Field
name={name}
type="number"
component={renderInputField}
placeholder={t(placeholder)}
disabled={processingSetConfig}
normalize={toNumber}
className="form-control"
validate={[validateBiggerOrEqualZeroValue].concat(validate || [])}
min={0}
max={max}
/>
</div>
</div>
</div>)}
{minExceedsMax
&& <span className="text-danger pl-3 pb-3">{t('min_exceeds_max_value')}</span>}
</div>
<button
type="submit"
className="btn btn-success btn-standard btn-large"
disabled={submitting || invalid || processingSetConfig || minExceedsMax}
>
<Trans>save_btn</Trans>
</button>
</form>;
};
Form.propTypes = {
handleSubmit: PropTypes.func.isRequired,
submitting: PropTypes.bool.isRequired,
invalid: PropTypes.bool.isRequired,
};
export default reduxForm({ form: FORM_NAME.CACHE })(Form);

View File

@ -0,0 +1,42 @@
import React from 'react';
import { useTranslation } from 'react-i18next';
import { shallowEqual, useDispatch, useSelector } from 'react-redux';
import Card from '../../../ui/Card';
import Form from './Form';
import { setDnsConfig } from '../../../../actions/dnsConfig';
import { selectCompletedFields } from '../../../../helpers/helpers';
const CacheConfig = () => {
const { t } = useTranslation();
const dispatch = useDispatch();
const {
cache_size, cache_ttl_max, cache_ttl_min,
} = useSelector((state) => state.dnsConfig, shallowEqual);
const handleFormSubmit = (values) => {
const completedFields = selectCompletedFields(values);
dispatch(setDnsConfig(completedFields));
};
return (
<Card
title={t('dns_cache_config')}
subtitle={t('dns_cache_config_desc')}
bodyType="card-body box-body--settings"
id="dns-config"
>
<div className="form">
<Form
initialValues={{
cache_size,
cache_ttl_max,
cache_ttl_min,
}}
onSubmit={handleFormSubmit}
/>
</div>
</Card>
);
};
export default CacheConfig;

View File

@ -4,17 +4,18 @@ import { connect } from 'react-redux';
import { Field, reduxForm, formValueSelector } from 'redux-form'; import { Field, reduxForm, formValueSelector } from 'redux-form';
import { Trans, withTranslation } from 'react-i18next'; import { Trans, withTranslation } from 'react-i18next';
import flow from 'lodash/flow'; import flow from 'lodash/flow';
import { import {
renderInputField, renderInputField,
renderRadioField, renderRadioField,
renderSelectField, renderSelectField,
required,
ipv4,
ipv6,
biggerOrEqualZero,
toNumber, toNumber,
} from '../../../../helpers/form'; } from '../../../../helpers/form';
import {
validateBiggerOrEqualZeroValue,
validateIpv4,
validateIpv6,
validateRequiredValue,
} from '../../../../helpers/validators';
import { BLOCKING_MODES, FORM_NAME } from '../../../../helpers/constants'; import { BLOCKING_MODES, FORM_NAME } from '../../../../helpers/constants';
const checkboxes = [{ const checkboxes = [{
@ -36,12 +37,12 @@ const checkboxes = [{
const customIps = [{ const customIps = [{
description: 'blocking_ipv4_desc', description: 'blocking_ipv4_desc',
name: 'blocking_ipv4', name: 'blocking_ipv4',
validateIp: ipv4, validateIp: validateIpv4,
}, },
{ {
description: 'blocking_ipv6_desc', description: 'blocking_ipv6_desc',
name: 'blocking_ipv6', name: 'blocking_ipv6',
validateIp: ipv6, validateIp: validateIpv6,
}]; }];
const getFields = (processing, t) => Object.values(BLOCKING_MODES) const getFields = (processing, t) => Object.values(BLOCKING_MODES)
@ -77,7 +78,7 @@ let Form = ({
className="form-control" className="form-control"
placeholder={t('form_enter_rate_limit')} placeholder={t('form_enter_rate_limit')}
normalize={toNumber} normalize={toNumber}
validate={[required, biggerOrEqualZero]} validate={[validateRequiredValue, validateBiggerOrEqualZeroValue]}
/> />
</div> </div>
</div> </div>
@ -130,7 +131,7 @@ let Form = ({
component={renderInputField} component={renderInputField}
className="form-control" className="form-control"
placeholder={t('form_enter_ip')} placeholder={t('form_enter_ip')}
validate={[validateIp, required]} validate={[validateIp, validateRequiredValue]}
/> />
</div> </div>
</div>)} </div>)}

View File

@ -7,9 +7,10 @@ import Access from './Access';
import Config from './Config'; import Config from './Config';
import PageTitle from '../../ui/PageTitle'; import PageTitle from '../../ui/PageTitle';
import Loading from '../../ui/Loading'; import Loading from '../../ui/Loading';
import CacheConfig from './Cache';
const Dns = (props) => { const Dns = (props) => {
const [t] = useTranslation(); const { t } = useTranslation();
useEffect(() => { useEffect(() => {
props.getAccessList(); props.getAccessList();
@ -40,6 +41,10 @@ const Dns = (props) => {
dnsConfig={dnsConfig} dnsConfig={dnsConfig}
setDnsConfig={setDnsConfig} setDnsConfig={setDnsConfig}
/> />
<CacheConfig
dnsConfig={dnsConfig}
setDnsConfig={setDnsConfig}
/>
<Access access={access} setAccessList={setAccessList} /> <Access access={access} setAccessList={setAccessList} />
</>} </>}
</> </>

View File

@ -10,10 +10,8 @@ import {
renderSelectField, renderSelectField,
renderRadioField, renderRadioField,
toNumber, toNumber,
port,
portTLS,
isSafePort,
} from '../../../helpers/form'; } from '../../../helpers/form';
import { validateIsSafePort, validatePort, validatePortTLS } from '../../../helpers/validators';
import i18n from '../../../i18n'; import i18n from '../../../i18n';
import KeyStatus from './KeyStatus'; import KeyStatus from './KeyStatus';
import CertificateStatus from './CertificateStatus'; import CertificateStatus from './CertificateStatus';
@ -46,7 +44,8 @@ const clearFields = (change, setTlsConfig, t) => {
}; };
// eslint-disable-next-line no-alert // eslint-disable-next-line no-alert
if (window.confirm(t('encryption_reset'))) { if (window.confirm(t('encryption_reset'))) {
Object.keys(fields).forEach((field) => change(field, fields[field])); Object.keys(fields)
.forEach((field) => change(field, fields[field]));
setTlsConfig(fields); setTlsConfig(fields);
} }
}; };
@ -158,7 +157,7 @@ let Form = (props) => {
type="number" type="number"
className="form-control" className="form-control"
placeholder={t('encryption_https')} placeholder={t('encryption_https')}
validate={[port, isSafePort]} validate={[validatePort, validateIsSafePort]}
normalize={toNumber} normalize={toNumber}
onChange={handleChange} onChange={handleChange}
disabled={!isEnabled} disabled={!isEnabled}
@ -180,7 +179,7 @@ let Form = (props) => {
type="number" type="number"
className="form-control" className="form-control"
placeholder={t('encryption_dot')} placeholder={t('encryption_dot')}
validate={[portTLS]} validate={[validatePortTLS]}
normalize={toNumber} normalize={toNumber}
onChange={handleChange} onChange={handleChange}
disabled={!isEnabled} disabled={!isEnabled}

View File

@ -501,6 +501,9 @@ export const FORM_NAME = {
STATS_CONFIG: 'statsConfig', STATS_CONFIG: 'statsConfig',
INSTALL: 'install', INSTALL: 'install',
LOGIN: 'login', LOGIN: 'login',
CACHE: 'cache',
}; };
export const smallScreenSize = 767; export const smallScreenSize = 767;
export const SECONDS_IN_HOUR = 60 * 60;

View File

@ -1,16 +1,12 @@
import React, { Fragment } from 'react'; import React, { Fragment } from 'react';
import { Trans } from 'react-i18next';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
import {
R_IPV4, R_MAC, R_HOST, R_IPV6, R_CIDR, R_CIDR_IPV6,
UNSAFE_PORTS, R_URL_REQUIRES_PROTOCOL, R_WIN_ABSOLUTE_PATH, R_UNIX_ABSOLUTE_PATH,
} from './constants';
import { createOnBlurHandler } from './helpers'; import { createOnBlurHandler } from './helpers';
import { R_UNIX_ABSOLUTE_PATH, R_WIN_ABSOLUTE_PATH } from './constants';
export const renderField = (props, elementType) => { export const renderField = (props, elementType) => {
const { const {
input, id, className, placeholder, type, disabled, normalizeOnBlur, input, id, className, placeholder, type, disabled, normalizeOnBlur,
autoComplete, meta: { touched, error }, autoComplete, meta: { touched, error }, min, max, step,
} = props; } = props;
const onBlur = (event) => createOnBlurHandler(event, input, normalizeOnBlur); const onBlur = (event) => createOnBlurHandler(event, input, normalizeOnBlur);
@ -23,14 +19,17 @@ export const renderField = (props, elementType) => {
autoComplete, autoComplete,
disabled, disabled,
type, type,
min,
max,
step,
onBlur, onBlur,
}); });
return ( return (
<Fragment> <>
{element} {element}
{!disabled && touched && error {!disabled && touched && error
&& <span className="form__message form__message--error">{error}</span>} && <span className="form__message form__message--error">{error}</span>}
</Fragment> </>
); );
}; };
@ -43,6 +42,9 @@ renderField.propTypes = {
disabled: PropTypes.bool, disabled: PropTypes.bool,
autoComplete: PropTypes.bool, autoComplete: PropTypes.bool,
normalizeOnBlur: PropTypes.func, normalizeOnBlur: PropTypes.func,
min: PropTypes.number,
max: PropTypes.number,
step: PropTypes.number,
meta: PropTypes.shape({ meta: PropTypes.shape({
touched: PropTypes.bool, touched: PropTypes.bool,
error: PropTypes.object, error: PropTypes.object,
@ -227,136 +229,15 @@ renderServiceField.propTypes = {
}).isRequired, }).isRequired,
}; };
// Validation functions /**
// If the value is valid, the validation function should return undefined. * @param value {string}
// https://redux-form.com/6.6.3/examples/fieldlevelvalidation/ * @returns {*|number}
export const required = (value) => { */
const formattedValue = typeof value === 'string' ? value.trim() : value; export const toNumber = (value) => value && parseInt(value, 10);
if (formattedValue || formattedValue === 0 || formattedValue?.length !== 0) {
return undefined;
}
return <Trans>form_error_required</Trans>;
};
export const ipv4 = (value) => {
if (value && !R_IPV4.test(value)) {
return <Trans>form_error_ip4_format</Trans>;
}
return undefined;
};
export const clientId = (value) => {
if (!value) {
return undefined;
}
const formattedValue = value ? value.trim() : value;
if (formattedValue && !(
R_IPV4.test(formattedValue)
|| R_IPV6.test(formattedValue)
|| R_MAC.test(formattedValue)
|| R_CIDR.test(formattedValue)
|| R_CIDR_IPV6.test(formattedValue)
)) {
return <Trans>form_error_client_id_format</Trans>;
}
return undefined;
};
export const ipv6 = (value) => {
if (value && !R_IPV6.test(value)) {
return <Trans>form_error_ip6_format</Trans>;
}
return undefined;
};
export const ip = (value) => {
if (value && !R_IPV4.test(value) && !R_IPV6.test(value)) {
return <Trans>form_error_ip_format</Trans>;
}
return undefined;
};
export const mac = (value) => {
if (value && !R_MAC.test(value)) {
return <Trans>form_error_mac_format</Trans>;
}
return undefined;
};
export const isPositive = (value) => {
if ((value || value === 0) && value <= 0) {
return <Trans>form_error_positive</Trans>;
}
return undefined;
};
export const biggerOrEqualZero = (value) => {
if (value < 0) {
return <Trans>form_error_negative</Trans>;
}
return false;
};
export const port = (value) => {
if ((value || value === 0) && (value < 80 || value > 65535)) {
return <Trans>form_error_port_range</Trans>;
}
return undefined;
};
export const validInstallPort = (value) => {
if (value < 1 || value > 65535) {
return <Trans>form_error_port</Trans>;
}
return undefined;
};
export const portTLS = (value) => {
if (value === 0) {
return undefined;
}
if (value && (value < 80 || value > 65535)) {
return <Trans>form_error_port_range</Trans>;
}
return undefined;
};
export const isSafePort = (value) => {
if (UNSAFE_PORTS.includes(value)) {
return <Trans>form_error_port_unsafe</Trans>;
}
return undefined;
};
export const domain = (value) => {
if (value && !R_HOST.test(value)) {
return <Trans>form_error_domain_format</Trans>;
}
return undefined;
};
export const answer = (value) => {
if (value && (!R_IPV4.test(value) && !R_IPV6.test(value) && !R_HOST.test(value))) {
return <Trans>form_error_answer_format</Trans>;
}
return undefined;
};
export const isValidUrl = (value) => {
if (value && !R_URL_REQUIRES_PROTOCOL.test(value)) {
return <Trans>form_error_url_format</Trans>;
}
return undefined;
};
/**
* @param value {string}
* @returns {boolean}
*/
export const isValidAbsolutePath = (value) => R_WIN_ABSOLUTE_PATH.test(value) export const isValidAbsolutePath = (value) => R_WIN_ABSOLUTE_PATH.test(value)
|| R_UNIX_ABSOLUTE_PATH.test(value); || R_UNIX_ABSOLUTE_PATH.test(value);
export const isValidPath = (value) => {
if (value && !isValidAbsolutePath(value) && !R_URL_REQUIRES_PROTOCOL.test(value)) {
return <Trans>form_error_url_or_path_format</Trans>;
}
return undefined;
};
export const toNumber = (value) => value && parseInt(value, 10);

View File

@ -595,3 +595,15 @@ export const formatElapsedMs = (elapsedMs, t) => {
export const setHtmlLangAttr = (language) => { export const setHtmlLangAttr = (language) => {
window.document.documentElement.lang = language; window.document.documentElement.lang = language;
}; };
/**
* @param values {object}
* @returns {object}
*/
export const selectCompletedFields = (values) => Object.entries(values)
.reduce((acc, [key, value]) => {
if (value || value === 0) {
acc[key] = value;
}
return acc;
}, {});

View File

@ -0,0 +1,209 @@
import { Trans } from 'react-i18next';
import React from 'react';
import i18next from 'i18next';
import {
R_CIDR,
R_CIDR_IPV6,
R_HOST,
R_IPV4,
R_IPV6,
R_MAC,
R_URL_REQUIRES_PROTOCOL,
UNSAFE_PORTS,
} from './constants';
import { isValidAbsolutePath } from './form';
// Validation functions
// https://redux-form.com/8.3.0/examples/fieldlevelvalidation/
// If the value is valid, the validation function should return undefined.
/**
* @param value {string}
* @returns {undefined|string}
*/
export const validateRequiredValue = (value) => {
const formattedValue = typeof value === 'string' ? value.trim() : value;
if (formattedValue || formattedValue === 0 || (formattedValue && formattedValue.length !== 0)) {
return undefined;
}
return <Trans>form_error_required</Trans>;
};
/**
* @param maximum {number}
* @returns {(value:number) => undefined|string}
*/
export const getMaxValueValidator = (maximum) => (value) => {
if (value && value > maximum) {
i18next.t('value_not_larger_than', { maximum });
}
return undefined;
};
/**
* @param value {string}
* @returns {undefined|string}
*/
export const validateIpv4 = (value) => {
if (value && !R_IPV4.test(value)) {
return <Trans>form_error_ip4_format</Trans>;
}
return undefined;
};
/**
* @param value {string}
* @returns {undefined|string}
*/
export const validateClientId = (value) => {
if (!value) {
return undefined;
}
const formattedValue = value ? value.trim() : value;
if (formattedValue && !(
R_IPV4.test(formattedValue)
|| R_IPV6.test(formattedValue)
|| R_MAC.test(formattedValue)
|| R_CIDR.test(formattedValue)
|| R_CIDR_IPV6.test(formattedValue)
)) {
return <Trans>form_error_client_id_format</Trans>;
}
return undefined;
};
/**
* @param value {string}
* @returns {undefined|string}
*/
export const validateIpv6 = (value) => {
if (value && !R_IPV6.test(value)) {
return <Trans>form_error_ip6_format</Trans>;
}
return undefined;
};
/**
* @param value {string}
* @returns {undefined|string}
*/
export const validateIp = (value) => {
if (value && !R_IPV4.test(value) && !R_IPV6.test(value)) {
return <Trans>form_error_ip_format</Trans>;
}
return undefined;
};
/**
* @param value {string}
* @returns {undefined|string}
*/
export const validateMac = (value) => {
if (value && !R_MAC.test(value)) {
return <Trans>form_error_mac_format</Trans>;
}
return undefined;
};
/**
* @param value {string}
* @returns {undefined|string}
*/
export const validateIsPositiveValue = (value) => {
if ((value || value === 0) && value <= 0) {
return <Trans>form_error_positive</Trans>;
}
return undefined;
};
/**
* @param value {string}
* @returns {boolean|*}
*/
export const validateBiggerOrEqualZeroValue = (value) => {
if (value < 0) {
return <Trans>form_error_negative</Trans>;
}
return false;
};
/**
* @param value {string}
* @returns {undefined|string}
*/
export const validatePort = (value) => {
if ((value || value === 0) && (value < 80 || value > 65535)) {
return <Trans>form_error_port_range</Trans>;
}
return undefined;
};
/**
* @param value {string}
* @returns {undefined|string}
*/
export const validateInstallPort = (value) => {
if (value < 1 || value > 65535) {
return <Trans>form_error_port</Trans>;
}
return undefined;
};
/**
* @param value {string}
* @returns {undefined|string}
*/
export const validatePortTLS = (value) => {
if (value === 0) {
return undefined;
}
if (value && (value < 80 || value > 65535)) {
return <Trans>form_error_port_range</Trans>;
}
return undefined;
};
/**
* @param value {string}
* @returns {undefined|string}
*/
export const validateIsSafePort = (value) => {
if (UNSAFE_PORTS.includes(value)) {
return <Trans>form_error_port_unsafe</Trans>;
}
return undefined;
};
/**
* @param value {string}
* @returns {undefined|string}
*/
export const validateDomain = (value) => {
if (value && !R_HOST.test(value)) {
return <Trans>form_error_domain_format</Trans>;
}
return undefined;
};
/**
* @param value {string}
* @returns {undefined|string}
*/
export const validateAnswer = (value) => {
if (value && (!R_IPV4.test(value) && !R_IPV6.test(value) && !R_HOST.test(value))) {
return <Trans>form_error_answer_format</Trans>;
}
return undefined;
};
/**
* @param value {string}
* @returns {undefined|string}
*/
export const validatePath = (value) => {
if (value && !isValidAbsolutePath(value) && !R_URL_REQUIRES_PROTOCOL.test(value)) {
return <Trans>form_error_url_or_path_format</Trans>;
}
return undefined;
};

View File

@ -10,9 +10,8 @@ import AddressList from './AddressList';
import { getInterfaceIp } from '../../helpers/helpers'; import { getInterfaceIp } from '../../helpers/helpers';
import { ALL_INTERFACES_IP, FORM_NAME } from '../../helpers/constants'; import { ALL_INTERFACES_IP, FORM_NAME } from '../../helpers/constants';
import { import { renderInputField, toNumber } from '../../helpers/form';
renderInputField, required, validInstallPort, toNumber, import { validateRequiredValue, validateInstallPort } from '../../helpers/validators';
} from '../../helpers/form';
const STATIC_STATUS = { const STATIC_STATUS = {
ENABLED: 'yes', ENABLED: 'yes',
@ -212,7 +211,7 @@ class Settings extends Component {
type="number" type="number"
className="form-control" className="form-control"
placeholder="80" placeholder="80"
validate={[validInstallPort, required]} validate={[validateInstallPort, validateRequiredValue]}
normalize={toNumber} normalize={toNumber}
onChange={handleChange} onChange={handleChange}
/> />
@ -282,7 +281,7 @@ class Settings extends Component {
type="number" type="number"
className="form-control" className="form-control"
placeholder="80" placeholder="80"
validate={[validInstallPort, required]} validate={[validateInstallPort, validateRequiredValue]}
normalize={toNumber} normalize={toNumber}
onChange={handleChange} onChange={handleChange}
/> />

View File

@ -3,8 +3,8 @@ import PropTypes from 'prop-types';
import { Field, reduxForm } from 'redux-form'; import { Field, reduxForm } from 'redux-form';
import { Trans, withTranslation } from 'react-i18next'; import { Trans, withTranslation } from 'react-i18next';
import flow from 'lodash/flow'; import flow from 'lodash/flow';
import { renderInputField } from '../../helpers/form';
import { renderInputField, required } from '../../helpers/form'; import { validateRequiredValue } from '../../helpers/validators';
import { FORM_NAME } from '../../helpers/constants'; import { FORM_NAME } from '../../helpers/constants';
const Form = (props) => { const Form = (props) => {
@ -28,7 +28,7 @@ const Form = (props) => {
placeholder={t('username_placeholder')} placeholder={t('username_placeholder')}
autoComplete="username" autoComplete="username"
disabled={processing} disabled={processing}
validate={[required]} validate={[validateRequiredValue]}
/> />
</div> </div>
<div className="form__group form__group--settings"> <div className="form__group form__group--settings">
@ -44,7 +44,7 @@ const Form = (props) => {
placeholder={t('password_placeholder')} placeholder={t('password_placeholder')}
autoComplete="current-password" autoComplete="current-password"
disabled={processing} disabled={processing}
validate={[required]} validate={[validateRequiredValue]}
/> />
</div> </div>
<div className="form-footer"> <div className="form-footer">