Merge: + client: add clients forms validation and cache findClients function

* commit '2e493e0226d3f22941fd09eed44ebb67a4d2874a':
  + client: add clients forms validation and cache findClients function
This commit is contained in:
Andrey Meshkov 2019-12-20 16:15:04 +03:00
commit 28096d6966
16 changed files with 187 additions and 162 deletions

View File

@ -23,6 +23,7 @@
"form_error_ip6_format": "Invalid IPv6 format", "form_error_ip6_format": "Invalid IPv6 format",
"form_error_ip_format": "Invalid IP format", "form_error_ip_format": "Invalid IP format",
"form_error_mac_format": "Invalid MAC format", "form_error_mac_format": "Invalid MAC format",
"form_error_client_id_format": "Invalid client ID format",
"form_error_positive": "Must be greater than 0", "form_error_positive": "Must be greater than 0",
"form_error_negative": "Must be equal to 0 or greater", "form_error_negative": "Must be equal to 0 or greater",
"dhcp_form_gateway_input": "Gateway IP", "dhcp_form_gateway_input": "Gateway IP",

View File

@ -5,20 +5,28 @@ import { addErrorToast, addSuccessToast } from './index';
import { normalizeLogs, getParamsForClientsSearch, addClientInfo } from '../helpers/helpers'; import { normalizeLogs, getParamsForClientsSearch, addClientInfo } from '../helpers/helpers';
import { TABLE_DEFAULT_PAGE_SIZE } from '../helpers/constants'; import { TABLE_DEFAULT_PAGE_SIZE } from '../helpers/constants';
const getLogsWithParams = async (config) => { // Cache clients in closure
const getLogsWithParamsWrapper = () => {
let clients = {};
return async (config) => {
const { older_than, filter, ...values } = config; const { older_than, filter, ...values } = config;
const rawLogs = await apiClient.getQueryLog({ ...filter, older_than }); const rawLogs = await apiClient.getQueryLog({ ...filter, older_than });
const { data, oldest } = rawLogs; const { data, oldest } = rawLogs;
const logs = normalizeLogs(data); const logs = normalizeLogs(data);
const clientsParams = getParamsForClientsSearch(logs, 'client'); const clientsParams = getParamsForClientsSearch(logs, 'client');
const clients = await apiClient.findClients(clientsParams); if (!Object.values(clientsParams).every(client => client in clients)) {
clients = await apiClient.findClients(clientsParams);
}
const logsWithClientInfo = addClientInfo(logs, clients, 'client'); const logsWithClientInfo = addClientInfo(logs, clients, 'client');
return { return {
logs: logsWithClientInfo, oldest, older_than, filter, ...values, logs: logsWithClientInfo, oldest, older_than, filter, ...values,
}; };
};
}; };
const getLogsWithParams = getLogsWithParamsWrapper();
export const getAdditionalLogsRequest = createAction('GET_ADDITIONAL_LOGS_REQUEST'); export const getAdditionalLogsRequest = createAction('GET_ADDITIONAL_LOGS_REQUEST');
export const getAdditionalLogsFailure = createAction('GET_ADDITIONAL_LOGS_FAILURE'); export const getAdditionalLogsFailure = createAction('GET_ADDITIONAL_LOGS_FAILURE');
export const getAdditionalLogsSuccess = createAction('GET_ADDITIONAL_LOGS_SUCCESS'); export const getAdditionalLogsSuccess = createAction('GET_ADDITIONAL_LOGS_SUCCESS');

View File

@ -39,13 +39,18 @@ export const getStatsRequest = createAction('GET_STATS_REQUEST');
export const getStatsFailure = createAction('GET_STATS_FAILURE'); export const getStatsFailure = createAction('GET_STATS_FAILURE');
export const getStatsSuccess = createAction('GET_STATS_SUCCESS'); export const getStatsSuccess = createAction('GET_STATS_SUCCESS');
export const getStats = () => async (dispatch) => { // Cache clients in closure
const getStatsWrapper = () => {
let clients = {};
return () => async (dispatch) => {
dispatch(getStatsRequest()); dispatch(getStatsRequest());
try { try {
const stats = await apiClient.getStats(); const stats = await apiClient.getStats();
const normalizedTopClients = normalizeTopStats(stats.top_clients); const normalizedTopClients = normalizeTopStats(stats.top_clients);
const clientsParams = getParamsForClientsSearch(normalizedTopClients, 'name'); const clientsParams = getParamsForClientsSearch(normalizedTopClients, 'name');
const clients = await apiClient.findClients(clientsParams); if (!Object.values(clientsParams).every(client => client in clients)) {
clients = await apiClient.findClients(clientsParams);
}
const topClientsWithInfo = addClientInfo(normalizedTopClients, clients, 'name'); const topClientsWithInfo = addClientInfo(normalizedTopClients, clients, 'name');
const normalizedStats = { const normalizedStats = {
@ -61,8 +66,11 @@ export const getStats = () => async (dispatch) => {
dispatch(addErrorToast({ error })); dispatch(addErrorToast({ error }));
dispatch(getStatsFailure()); dispatch(getStatsFailure());
} }
};
}; };
export const getStats = getStatsWrapper();
export const resetStatsRequest = createAction('RESET_STATS_REQUEST'); export const resetStatsRequest = createAction('RESET_STATS_REQUEST');
export const resetStatsFailure = createAction('RESET_STATS_FAILURE'); export const resetStatsFailure = createAction('RESET_STATS_FAILURE');
export const resetStatsSuccess = createAction('RESET_STATS_SUCCESS'); export const resetStatsSuccess = createAction('RESET_STATS_SUCCESS');

View File

@ -4,7 +4,7 @@ import { Field, reduxForm } from 'redux-form';
import { withNamespaces, Trans } from 'react-i18next'; import { withNamespaces, Trans } from 'react-i18next';
import flow from 'lodash/flow'; import flow from 'lodash/flow';
import { renderField } from '../../../helpers/form'; import { renderInputField } from '../../../helpers/form';
import { RESPONSE_FILTER } from '../../../helpers/constants'; import { RESPONSE_FILTER } from '../../../helpers/constants';
import Tooltip from '../../ui/Tooltip'; import Tooltip from '../../ui/Tooltip';
@ -65,7 +65,7 @@ const Form = (props) => {
<Field <Field
id="filter_question_type" id="filter_question_type"
name="filter_question_type" name="filter_question_type"
component={renderField} component={renderInputField}
type="text" type="text"
className="form-control" className="form-control"
placeholder={t('type_table_header')} placeholder={t('type_table_header')}

View File

@ -10,7 +10,9 @@ 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 {
renderField, required,
clientId,
renderInputField,
renderGroupField, renderGroupField,
renderSelectField, renderSelectField,
renderServiceField, renderServiceField,
@ -40,38 +42,30 @@ const settingsCheckboxes = [
placeholder: 'enforce_safe_search', placeholder: 'enforce_safe_search',
}, },
]; ];
const validate = (values) => { const validate = (values) => {
const errors = {}; const errors = {};
const { name, ids } = values; const { name, ids } = values;
errors.name = required(name);
if (!name || !name.length) {
errors.name = i18n.t('form_error_required');
}
if (ids && ids.length) { if (ids && ids.length) {
const idArrayErrors = []; const idArrayErrors = [];
ids.forEach((id, idx) => { ids.forEach((id, idx) => {
if (!id || !id.length) { idArrayErrors[idx] = required(id) || clientId(id);
idArrayErrors[idx] = i18n.t('form_error_required');
}
}); });
if (idArrayErrors.length) { if (idArrayErrors.length) {
errors.ids = idArrayErrors; errors.ids = idArrayErrors;
} }
} }
return errors; return errors;
}; };
const renderFields = (placeholder, buttonTitle) =>
const renderFieldsWrapper = (placeholder, buttonTitle) =>
function cell(row) { function cell(row) {
const { const {
fields, fields,
meta: { error },
} = row; } = row;
return ( return (
<div className="form__group"> <div className="form__group">
{fields.map((ip, index) => ( {fields.map((ip, index) => (
@ -84,6 +78,7 @@ const renderFields = (placeholder, buttonTitle) =>
placeholder={placeholder} placeholder={placeholder}
isActionAvailable={index !== 0} isActionAvailable={index !== 0}
removeField={() => fields.remove(index)} removeField={() => fields.remove(index)}
normalize={data => data && data.trim()}
/> />
</div> </div>
))} ))}
@ -97,11 +92,13 @@ const renderFields = (placeholder, buttonTitle) =>
<use xlinkHref="#plus" /> <use xlinkHref="#plus" />
</svg> </svg>
</button> </button>
{error && <div className="error">{error}</div>}
</div> </div>
); );
}; };
// Should create function outside of component to prevent component re-renders
const renderFields = renderFieldsWrapper(i18n.t('form_enter_id'), i18n.t('form_add_id'));
let Form = (props) => { let Form = (props) => {
const { const {
t, t,
@ -126,10 +123,11 @@ let Form = (props) => {
<Field <Field
id="name" id="name"
name="name" name="name"
component={renderField} component={renderInputField}
type="text" type="text"
className="form-control" className="form-control"
placeholder={t('form_client_name')} placeholder={t('form_client_name')}
normalize={data => data && data.trim()}
/> />
</div> </div>
@ -155,7 +153,7 @@ let Form = (props) => {
<div className="form__group"> <div className="form__group">
<FieldArray <FieldArray
name="ids" name="ids"
component={renderFields(t('form_enter_id'), t('form_add_id'))} component={renderFields}
/> />
</div> </div>
</div> </div>

View File

@ -5,7 +5,7 @@ import { Field, reduxForm, formValueSelector } from 'redux-form';
import { Trans, withNamespaces } from 'react-i18next'; import { Trans, withNamespaces } from 'react-i18next';
import flow from 'lodash/flow'; import flow from 'lodash/flow';
import { renderField, required, ipv4, isPositive, toNumber } from '../../../helpers/form'; import { renderInputField, required, ipv4, isPositive, toNumber } from '../../../helpers/form';
const renderInterfaces = (interfaces => ( const renderInterfaces = (interfaces => (
Object.keys(interfaces).map((item) => { Object.keys(interfaces).map((item) => {
@ -116,8 +116,9 @@ let Form = (props) => {
<div className="form__group form__group--settings"> <div className="form__group form__group--settings">
<label>{t('dhcp_form_gateway_input')}</label> <label>{t('dhcp_form_gateway_input')}</label>
<Field <Field
id="gateway_ip"
name="gateway_ip" name="gateway_ip"
component={renderField} component={renderInputField}
type="text" type="text"
className="form-control" className="form-control"
placeholder={t('dhcp_form_gateway_input')} placeholder={t('dhcp_form_gateway_input')}
@ -127,8 +128,9 @@ let Form = (props) => {
<div className="form__group form__group--settings"> <div className="form__group form__group--settings">
<label>{t('dhcp_form_subnet_input')}</label> <label>{t('dhcp_form_subnet_input')}</label>
<Field <Field
id="subnet_mask"
name="subnet_mask" name="subnet_mask"
component={renderField} component={renderInputField}
type="text" type="text"
className="form-control" className="form-control"
placeholder={t('dhcp_form_subnet_input')} placeholder={t('dhcp_form_subnet_input')}
@ -144,8 +146,9 @@ let Form = (props) => {
</div> </div>
<div className="col"> <div className="col">
<Field <Field
id="range_start"
name="range_start" name="range_start"
component={renderField} component={renderInputField}
type="text" type="text"
className="form-control" className="form-control"
placeholder={t('dhcp_form_range_start')} placeholder={t('dhcp_form_range_start')}
@ -154,8 +157,9 @@ let Form = (props) => {
</div> </div>
<div className="col"> <div className="col">
<Field <Field
id="range_end"
name="range_end" name="range_end"
component={renderField} component={renderInputField}
type="text" type="text"
className="form-control" className="form-control"
placeholder={t('dhcp_form_range_end')} placeholder={t('dhcp_form_range_end')}
@ -168,7 +172,7 @@ let Form = (props) => {
<label>{t('dhcp_form_lease_title')}</label> <label>{t('dhcp_form_lease_title')}</label>
<Field <Field
name="lease_duration" name="lease_duration"
component={renderField} component={renderInputField}
type="number" type="number"
className="form-control" className="form-control"
placeholder={t('dhcp_form_lease_input')} placeholder={t('dhcp_form_lease_input')}

View File

@ -4,7 +4,7 @@ import { Field, reduxForm } from 'redux-form';
import { Trans, withNamespaces } from 'react-i18next'; import { Trans, withNamespaces } from 'react-i18next';
import flow from 'lodash/flow'; import flow from 'lodash/flow';
import { renderField, ipv4, mac, required } from '../../../../helpers/form'; import { renderInputField, ipv4, mac, required } from '../../../../helpers/form';
const Form = (props) => { const Form = (props) => {
const { const {
@ -24,7 +24,7 @@ const Form = (props) => {
<Field <Field
id="mac" id="mac"
name="mac" name="mac"
component={renderField} component={renderInputField}
type="text" type="text"
className="form-control" className="form-control"
placeholder={t('form_enter_mac')} placeholder={t('form_enter_mac')}
@ -35,7 +35,7 @@ const Form = (props) => {
<Field <Field
id="ip" id="ip"
name="ip" name="ip"
component={renderField} component={renderInputField}
type="text" type="text"
className="form-control" className="form-control"
placeholder={t('form_enter_ip')} placeholder={t('form_enter_ip')}
@ -46,7 +46,7 @@ const Form = (props) => {
<Field <Field
id="hostname" id="hostname"
name="hostname" name="hostname"
component={renderField} component={renderInputField}
type="text" type="text"
className="form-control" className="form-control"
placeholder={t('form_enter_hostname')} placeholder={t('form_enter_hostname')}

View File

@ -3,6 +3,7 @@ import PropTypes from 'prop-types';
import { Field, reduxForm } from 'redux-form'; import { Field, reduxForm } from 'redux-form';
import { Trans, withNamespaces } from 'react-i18next'; import { Trans, withNamespaces } from 'react-i18next';
import flow from 'lodash/flow'; import flow from 'lodash/flow';
import { renderTextareaField } from '../../../../helpers/form';
const Form = (props) => { const Form = (props) => {
const { const {
@ -21,7 +22,7 @@ const Form = (props) => {
<Field <Field
id="allowed_clients" id="allowed_clients"
name="allowed_clients" name="allowed_clients"
component="textarea" component={renderTextareaField}
type="text" type="text"
className="form-control form-control--textarea" className="form-control form-control--textarea"
disabled={processingSet} disabled={processingSet}
@ -37,7 +38,7 @@ const Form = (props) => {
<Field <Field
id="disallowed_clients" id="disallowed_clients"
name="disallowed_clients" name="disallowed_clients"
component="textarea" component={renderTextareaField}
type="text" type="text"
className="form-control form-control--textarea" className="form-control form-control--textarea"
disabled={processingSet} disabled={processingSet}
@ -53,7 +54,7 @@ const Form = (props) => {
<Field <Field
id="blocked_hosts" id="blocked_hosts"
name="blocked_hosts" name="blocked_hosts"
component="textarea" component={renderTextareaField}
type="text" type="text"
className="form-control form-control--textarea" className="form-control form-control--textarea"
disabled={processingSet} disabled={processingSet}
@ -81,6 +82,7 @@ Form.propTypes = {
initialValues: PropTypes.object.isRequired, initialValues: PropTypes.object.isRequired,
processingSet: PropTypes.bool.isRequired, processingSet: PropTypes.bool.isRequired,
t: PropTypes.func.isRequired, t: PropTypes.func.isRequired,
textarea: PropTypes.bool,
}; };
export default flow([withNamespaces(), reduxForm({ form: 'accessForm' })])(Form); export default flow([withNamespaces(), reduxForm({ form: 'accessForm' })])(Form);

View File

@ -4,7 +4,7 @@ import { Field, reduxForm } from 'redux-form';
import { Trans, withNamespaces } from 'react-i18next'; import { Trans, withNamespaces } from 'react-i18next';
import flow from 'lodash/flow'; import flow from 'lodash/flow';
import { renderField, required, domain, answer } from '../../../../helpers/form'; import { renderInputField, required, domain, answer } from '../../../../helpers/form';
const Form = (props) => { const Form = (props) => {
const { const {
@ -24,7 +24,7 @@ const Form = (props) => {
<Field <Field
id="domain" id="domain"
name="domain" name="domain"
component={renderField} component={renderInputField}
type="text" type="text"
className="form-control" className="form-control"
placeholder={t('form_domain')} placeholder={t('form_domain')}
@ -35,7 +35,7 @@ const Form = (props) => {
<Field <Field
id="answer" id="answer"
name="answer" name="answer"
component={renderField} component={renderInputField}
type="text" type="text"
className="form-control" className="form-control"
placeholder={t('form_answer')} placeholder={t('form_answer')}

View File

@ -6,7 +6,7 @@ import { Trans, withNamespaces } from 'react-i18next';
import flow from 'lodash/flow'; import flow from 'lodash/flow';
import { import {
renderField, renderInputField,
renderSelectField, renderSelectField,
renderRadioField, renderRadioField,
toNumber, toNumber,
@ -117,7 +117,7 @@ let Form = (props) => {
<Field <Field
id="server_name" id="server_name"
name="server_name" name="server_name"
component={renderField} component={renderInputField}
type="text" type="text"
className="form-control" className="form-control"
placeholder={t('encryption_server_enter')} placeholder={t('encryption_server_enter')}
@ -154,7 +154,7 @@ let Form = (props) => {
<Field <Field
id="port_https" id="port_https"
name="port_https" name="port_https"
component={renderField} component={renderInputField}
type="number" type="number"
className="form-control" className="form-control"
placeholder={t('encryption_https')} placeholder={t('encryption_https')}
@ -176,7 +176,7 @@ let Form = (props) => {
<Field <Field
id="port_dns_over_tls" id="port_dns_over_tls"
name="port_dns_over_tls" name="port_dns_over_tls"
component={renderField} component={renderInputField}
type="number" type="number"
className="form-control" className="form-control"
placeholder={t('encryption_dot')} placeholder={t('encryption_dot')}
@ -252,7 +252,7 @@ let Form = (props) => {
<Field <Field
id="certificate_path" id="certificate_path"
name="certificate_path" name="certificate_path"
component={renderField} component={renderInputField}
type="text" type="text"
className="form-control" className="form-control"
placeholder={t('encryption_certificate_path')} placeholder={t('encryption_certificate_path')}
@ -321,7 +321,7 @@ let Form = (props) => {
<Field <Field
id="private_key_path" id="private_key_path"
name="private_key_path" name="private_key_path"
component={renderField} component={renderInputField}
type="text" type="text"
className="form-control" className="form-control"
placeholder={t('encryption_private_key_path')} placeholder={t('encryption_private_key_path')}

View File

@ -1,8 +1,9 @@
export const R_URL_REQUIRES_PROTOCOL = /^https?:\/\/[^/\s]+(\/.*)?$/; export const R_URL_REQUIRES_PROTOCOL = /^https?:\/\/[^/\s]+(\/.*)?$/;
export const R_HOST = /^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\\-]*[A-Za-z0-9])$/; export const R_HOST = /^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\\-]*[A-Za-z0-9])$/;
export const R_IPV4 = /^(?:(?:^|\.)(?:2(?:5[0-5]|[0-4]\d)|1?\d?\d)){4}$/g; export const R_IPV4 = /^(?:(?:^|\.)(?:2(?:5[0-5]|[0-4]\d)|1?\d?\d)){4}$/;
export const R_IPV6 = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))/g; export const R_IPV6 = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;
export const R_MAC = /^((([a-fA-F0-9][a-fA-F0-9]+[-]){5}|([a-fA-F0-9][a-fA-F0-9]+[:]){5})([a-fA-F0-9][a-fA-F0-9])$)|(^([a-fA-F0-9][a-fA-F0-9][a-fA-F0-9][a-fA-F0-9]+[.]){2}([a-fA-F0-9][a-fA-F0-9][a-fA-F0-9][a-fA-F0-9]))$/g; export const R_CIDR = /^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\/([0-9]|[1-2][0-9]|3[0-2]))$/;
export const R_MAC = /^((([a-fA-F0-9][a-fA-F0-9]+[-]){5}|([a-fA-F0-9][a-fA-F0-9]+[:]){5})([a-fA-F0-9][a-fA-F0-9])$)|(^([a-fA-F0-9][a-fA-F0-9][a-fA-F0-9][a-fA-F0-9]+[.]){2}([a-fA-F0-9][a-fA-F0-9][a-fA-F0-9][a-fA-F0-9]))$/;
export const STATS_NAMES = { export const STATS_NAMES = {
avg_processing_time: 'average_processing_time', avg_processing_time: 'average_processing_time',

View File

@ -1,33 +1,45 @@
import React, { Fragment } from 'react'; import React, { Fragment } from 'react';
import { Trans } from 'react-i18next'; import { Trans } from 'react-i18next';
import PropTypes from 'prop-types';
import { R_IPV4, R_MAC, R_HOST, R_IPV6, R_CIDR, UNSAFE_PORTS } from '../helpers/constants';
import { R_IPV4, R_MAC, R_HOST, R_IPV6, UNSAFE_PORTS } from '../helpers/constants'; export const renderField = (props, elementType) => {
const {
input, id, className, placeholder, type, disabled,
autoComplete, meta: { touched, error },
} = props;
export const renderField = ({ const element = React.createElement(elementType, {
input, ...input,
id, id,
className, className,
placeholder, placeholder,
type,
disabled,
autoComplete, autoComplete,
meta: { touched, error }, disabled,
}) => ( type,
});
return (
<Fragment> <Fragment>
<input {element}
{...input} {!disabled && touched && (error && <span className="form__message form__message--error">{error}</span>)}
id={id}
placeholder={placeholder}
type={type}
className={className}
disabled={disabled}
autoComplete={autoComplete}
/>
{!disabled &&
touched &&
(error && <span className="form__message form__message--error">{error}</span>)}
</Fragment> </Fragment>
); );
};
renderField.propTypes = {
id: PropTypes.string.isRequired,
input: PropTypes.object.isRequired,
meta: PropTypes.object.isRequired,
className: PropTypes.string,
placeholder: PropTypes.string,
type: PropTypes.string,
disabled: PropTypes.bool,
autoComplete: PropTypes.bool,
};
export const renderTextareaField = props => renderField(props, 'textarea');
export const renderInputField = props => renderField(props, 'input');
export const renderGroupField = ({ export const renderGroupField = ({
input, input,
@ -66,7 +78,6 @@ export const renderGroupField = ({
</span> </span>
} }
</div> </div>
{!disabled && {!disabled &&
touched && touched &&
(error && <span className="form__message form__message--error">{error}</span>)} (error && <span className="form__message form__message--error">{error}</span>)}
@ -147,46 +158,61 @@ export const renderServiceField = ({
); );
// Validation functions // Validation functions
// If the value is valid, the validation function should return undefined.
// https://redux-form.com/6.6.3/examples/fieldlevelvalidation/
export const required = (value) => { export const required = (value) => {
if (value || value === 0) { const formattedValue = typeof value === 'string' ? value.trim() : value;
return false; if (formattedValue || formattedValue === 0 || (formattedValue && formattedValue.length !== 0)) {
return undefined;
} }
return <Trans>form_error_required</Trans>; return <Trans>form_error_required</Trans>;
}; };
export const ipv4 = (value) => { export const ipv4 = (value) => {
if (value && !new RegExp(R_IPV4).test(value)) { if (value && !R_IPV4.test(value)) {
return <Trans>form_error_ip4_format</Trans>; return <Trans>form_error_ip4_format</Trans>;
} }
return false; 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))) {
return <Trans>form_error_client_id_format</Trans>;
}
return undefined;
}; };
export const ipv6 = (value) => { export const ipv6 = (value) => {
if (value && !new RegExp(R_IPV6).test(value)) { if (value && !R_IPV6.test(value)) {
return <Trans>form_error_ip6_format</Trans>; return <Trans>form_error_ip6_format</Trans>;
} }
return false; return undefined;
}; };
export const ip = (value) => { export const ip = (value) => {
if (value && !new RegExp(R_IPV4).test(value) && !new RegExp(R_IPV6).test(value)) { if (value && !R_IPV4.test(value) && !R_IPV6.test(value)) {
return <Trans>form_error_ip_format</Trans>; return <Trans>form_error_ip_format</Trans>;
} }
return false; return undefined;
}; };
export const mac = (value) => { export const mac = (value) => {
if (value && !new RegExp(R_MAC).test(value)) { if (value && !R_MAC.test(value)) {
return <Trans>form_error_mac_format</Trans>; return <Trans>form_error_mac_format</Trans>;
} }
return false; return undefined;
}; };
export const isPositive = (value) => { export const isPositive = (value) => {
if ((value || value === 0) && value <= 0) { if ((value || value === 0) && value <= 0) {
return <Trans>form_error_positive</Trans>; return <Trans>form_error_positive</Trans>;
} }
return false; return undefined;
}; };
export const biggerOrEqualZero = (value) => { export const biggerOrEqualZero = (value) => {
@ -200,42 +226,37 @@ export const port = (value) => {
if ((value || value === 0) && (value < 80 || value > 65535)) { if ((value || value === 0) && (value < 80 || value > 65535)) {
return <Trans>form_error_port_range</Trans>; return <Trans>form_error_port_range</Trans>;
} }
return false; return undefined;
}; };
export const portTLS = (value) => { export const portTLS = (value) => {
if (value === 0) { if (value === 0) {
return false; return undefined;
} else if (value && (value < 80 || value > 65535)) { } else if (value && (value < 80 || value > 65535)) {
return <Trans>form_error_port_range</Trans>; return <Trans>form_error_port_range</Trans>;
} }
return false; return undefined;
}; };
export const isSafePort = (value) => { export const isSafePort = (value) => {
if (UNSAFE_PORTS.includes(value)) { if (UNSAFE_PORTS.includes(value)) {
return <Trans>form_error_port_unsafe</Trans>; return <Trans>form_error_port_unsafe</Trans>;
} }
return false; return undefined;
}; };
export const domain = (value) => { export const domain = (value) => {
if (value && !new RegExp(R_HOST).test(value)) { if (value && !R_HOST.test(value)) {
return <Trans>form_error_domain_format</Trans>; return <Trans>form_error_domain_format</Trans>;
} }
return false; return undefined;
}; };
export const answer = (value) => { export const answer = (value) => {
if ( if (value && (!R_IPV4.test(value) && !R_IPV6.test(value) && !R_HOST.test(value))) {
value &&
(!new RegExp(R_IPV4).test(value) &&
!new RegExp(R_IPV6).test(value) &&
!new RegExp(R_HOST).test(value))
) {
return <Trans>form_error_answer_format</Trans>; return <Trans>form_error_answer_format</Trans>;
} }
return false; return undefined;
}; };
export const toNumber = value => value && parseInt(value, 10); export const toNumber = value => value && parseInt(value, 10);

View File

@ -6,7 +6,7 @@ import flow from 'lodash/flow';
import i18n from '../../i18n'; import i18n from '../../i18n';
import Controls from './Controls'; import Controls from './Controls';
import renderField from './renderField'; import { renderInputField } from '../../helpers/form';
const required = (value) => { const required = (value) => {
if (value || value === 0) { if (value || value === 0) {
@ -48,7 +48,7 @@ const Auth = (props) => {
</label> </label>
<Field <Field
name="username" name="username"
component={renderField} component={renderInputField}
type="text" type="text"
className="form-control" className="form-control"
placeholder={ t('install_auth_username_enter') } placeholder={ t('install_auth_username_enter') }
@ -62,7 +62,7 @@ const Auth = (props) => {
</label> </label>
<Field <Field
name="password" name="password"
component={renderField} component={renderInputField}
type="password" type="password"
className="form-control" className="form-control"
placeholder={ t('install_auth_password_enter') } placeholder={ t('install_auth_password_enter') }
@ -76,7 +76,7 @@ const Auth = (props) => {
</label> </label>
<Field <Field
name="confirm_password" name="confirm_password"
component={renderField} component={renderInputField}
type="password" type="password"
className="form-control" className="form-control"
placeholder={ t('install_auth_confirm') } placeholder={ t('install_auth_confirm') }

View File

@ -7,9 +7,9 @@ import flow from 'lodash/flow';
import Controls from './Controls'; import Controls from './Controls';
import AddressList from './AddressList'; import AddressList from './AddressList';
import renderField from './renderField';
import { getInterfaceIp } from '../../helpers/helpers'; import { getInterfaceIp } from '../../helpers/helpers';
import { ALL_INTERFACES_IP } from '../../helpers/constants'; import { ALL_INTERFACES_IP } from '../../helpers/constants';
import { renderInputField } from '../../helpers/form';
const required = (value) => { const required = (value) => {
if (value || value === 0) { if (value || value === 0) {
@ -133,7 +133,7 @@ class Settings extends Component {
</label> </label>
<Field <Field
name="web.port" name="web.port"
component={renderField} component={renderInputField}
type="number" type="number"
className="form-control" className="form-control"
placeholder="80" placeholder="80"
@ -201,7 +201,7 @@ class Settings extends Component {
</label> </label>
<Field <Field
name="dns.port" name="dns.port"
component={renderField} component={renderInputField}
type="number" type="number"
className="form-control" className="form-control"
placeholder="80" placeholder="80"

View File

@ -1,19 +0,0 @@
import React, { Fragment } from 'react';
const renderField = ({
input, className, placeholder, type, disabled, autoComplete, meta: { touched, error },
}) => (
<Fragment>
<input
{...input}
placeholder={placeholder}
type={type}
className={className}
disabled={disabled}
autoComplete={autoComplete}
/>
{!disabled && touched && (error && <span className="form__message form__message--error">{error}</span>)}
</Fragment>
);
export default renderField;

View File

@ -4,7 +4,7 @@ import { Field, reduxForm } from 'redux-form';
import { Trans, withNamespaces } from 'react-i18next'; import { Trans, withNamespaces } from 'react-i18next';
import flow from 'lodash/flow'; import flow from 'lodash/flow';
import { renderField, required } from '../../helpers/form'; import { renderInputField, required } from '../../helpers/form';
const Form = (props) => { const Form = (props) => {
const { const {
@ -19,10 +19,11 @@ const Form = (props) => {
<Trans>username_label</Trans> <Trans>username_label</Trans>
</label> </label>
<Field <Field
id="username1"
name="username" name="username"
type="text" type="text"
className="form-control" className="form-control"
component={renderField} component={renderInputField}
placeholder={t('username_placeholder')} placeholder={t('username_placeholder')}
autoComplete="username" autoComplete="username"
disabled={processing} disabled={processing}
@ -38,7 +39,7 @@ const Form = (props) => {
name="password" name="password"
type="password" type="password"
className="form-control" className="form-control"
component={renderField} component={renderInputField}
placeholder={t('password_placeholder')} placeholder={t('password_placeholder')}
autoComplete="current-password" autoComplete="current-password"
disabled={processing} disabled={processing}