Merge pull request #587 from mfrances17/fix-bind-type

LDAP Providers - do not show DN and Credentials when bind type is none
This commit is contained in:
mfrances17 2021-05-14 16:14:37 -04:00 committed by GitHub
commit 07e6628040
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 271 additions and 136 deletions

View file

@ -32,8 +32,6 @@ const secondLdapName = `${firstLdapName}-2`;
const secondLdapVendor = "Other"; const secondLdapVendor = "Other";
const secondBindType = "none"; const secondBindType = "none";
const secondBindDn = "user-2";
const secondBindCreds = "password2";
const secondUsersDn = "user-dn-2"; const secondUsersDn = "user-dn-2";
const secondUserLdapAtt = "cn"; const secondUserLdapAtt = "cn";
@ -165,8 +163,6 @@ describe("User Fed LDAP tests", () => {
providersPage.fillLdapRequiredConnectionData( providersPage.fillLdapRequiredConnectionData(
connectionUrl, connectionUrl,
secondBindType, secondBindType,
secondBindDn,
secondBindCreds
); );
providersPage.fillLdapRequiredSearchingData( providersPage.fillLdapRequiredSearchingData(
secondUsersDn, secondUsersDn,

View file

@ -129,8 +129,8 @@ export default class ProviderPage {
fillLdapRequiredConnectionData( fillLdapRequiredConnectionData(
connectionUrl: string, connectionUrl: string,
bindType: string, bindType: string,
bindDn: string, bindDn?: string,
bindCreds: string bindCreds?: string
) { ) {
if (connectionUrl) { if (connectionUrl) {
cy.get(`[${this.ldapConnectionUrlInput}]`).type(connectionUrl); cy.get(`[${this.ldapConnectionUrlInput}]`).type(connectionUrl);

View file

@ -26,7 +26,7 @@ import ComponentRepresentation from "keycloak-admin/lib/defs/componentRepresenta
import { Controller, useForm } from "react-hook-form"; import { Controller, useForm } from "react-hook-form";
import { useConfirmDialog } from "../components/confirm-dialog/ConfirmDialog"; import { useConfirmDialog } from "../components/confirm-dialog/ConfirmDialog";
import { useAdminClient } from "../context/auth/AdminClient"; import { asyncStateFetch, useAdminClient } from "../context/auth/AdminClient";
import { useAlerts } from "../components/alert/Alerts"; import { useAlerts } from "../components/alert/Alerts";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { ViewHeader } from "../components/view-header/ViewHeader"; import { ViewHeader } from "../components/view-header/ViewHeader";
@ -35,6 +35,14 @@ import { ScrollForm } from "../components/scroll-form/ScrollForm";
import { KeycloakTabs } from "../components/keycloak-tabs/KeycloakTabs"; import { KeycloakTabs } from "../components/keycloak-tabs/KeycloakTabs";
import { LdapMapperList } from "./ldap/mappers/LdapMapperList"; import { LdapMapperList } from "./ldap/mappers/LdapMapperList";
import { useErrorHandler } from "react-error-boundary";
type ldapComponentRepresentation = ComponentRepresentation & {
config?: {
periodicChangedUsersSync?: boolean;
periodicFullSync?: boolean;
};
};
type LdapSettingsHeaderProps = { type LdapSettingsHeaderProps = {
onChange: (value: string) => void; onChange: (value: string) => void;
@ -167,33 +175,45 @@ const LdapSettingsHeader = ({
export const UserFederationLdapSettings = () => { export const UserFederationLdapSettings = () => {
const { t } = useTranslation("user-federation"); const { t } = useTranslation("user-federation");
const form = useForm<ComponentRepresentation>(); const form = useForm<ComponentRepresentation>({ mode: "onChange" });
const history = useHistory(); const history = useHistory();
const adminClient = useAdminClient(); const adminClient = useAdminClient();
const { realm } = useRealm(); const { realm } = useRealm();
const errorHandler = useErrorHandler();
const { id } = useParams<{ id: string }>(); const { id } = useParams<{ id: string }>();
const { addAlert } = useAlerts(); const { addAlert } = useAlerts();
useEffect(() => { useEffect(() => {
(async () => { if (id) {
if (id) { return asyncStateFetch(
const fetchedComponent = await adminClient.components.findOne({ id }); () => adminClient.components.findOne({ id }),
if (fetchedComponent) { (fetchedComponent) => {
setupForm(fetchedComponent); if (fetchedComponent) {
} setupForm(fetchedComponent);
} }
})(); },
errorHandler
);
}
}, []); }, []);
const setupForm = (component: ComponentRepresentation) => { const setupForm = (component: ComponentRepresentation) => {
form.reset();
Object.entries(component).map((entry) => { Object.entries(component).map((entry) => {
if (entry[0] === "config") { if (entry[0] === "config") {
form.setValue(
"config.periodicChangedUsersSync",
entry[1].changedSyncPeriod[0] !== "-1"
);
form.setValue(
"config.periodicFullSync",
entry[1].fullSyncPeriod[0] !== "-1"
);
convertToFormValues(entry[1], "config", form.setValue); convertToFormValues(entry[1], "config", form.setValue);
} else {
form.setValue(entry[0], entry[1]);
} }
form.setValue(entry[0], entry[1]);
}); });
}; };
@ -208,7 +228,19 @@ export const UserFederationLdapSettings = () => {
} }
}; };
const save = async (component: ComponentRepresentation) => { const save = async (component: ldapComponentRepresentation) => {
if (component?.config?.periodicChangedUsersSync !== null) {
if (component?.config?.periodicChangedUsersSync === false) {
component.config.changedSyncPeriod = ["-1"];
}
delete component?.config?.periodicChangedUsersSync;
}
if (component?.config?.periodicFullSync !== null) {
if (component?.config?.periodicFullSync === false) {
component.config.fullSyncPeriod = ["-1"];
}
delete component?.config?.periodicFullSync;
}
try { try {
if (!id) { if (!id) {
await adminClient.components.create(component); await adminClient.components.create(component);
@ -216,11 +248,10 @@ export const UserFederationLdapSettings = () => {
} else { } else {
await adminClient.components.update({ id }, component); await adminClient.components.update({ id }, component);
} }
setupForm(component as ComponentRepresentation);
addAlert(t(id ? "saveSuccess" : "createSuccess"), AlertVariant.success); addAlert(t(id ? "saveSuccess" : "createSuccess"), AlertVariant.success);
} catch (error) { } catch (error) {
addAlert( addAlert(
`${t(id ? "saveError" : "createError")} '${error}'`, t(id ? "saveError" : "createError", { error }),
AlertVariant.danger AlertVariant.danger
); );
} }

View file

@ -1,4 +1,5 @@
import { import {
AlertVariant,
Button, Button,
FormGroup, FormGroup,
Select, Select,
@ -6,14 +7,21 @@ import {
SelectVariant, SelectVariant,
Switch, Switch,
TextInput, TextInput,
ValidatedOptions,
} from "@patternfly/react-core"; } from "@patternfly/react-core";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import React, { useState } from "react"; import React, { useState } from "react";
import _ from "lodash";
import TestLdapConnectionRepresentation from "keycloak-admin/lib/defs/testLdapConnection";
import { HelpItem } from "../../components/help-enabler/HelpItem"; import { HelpItem } from "../../components/help-enabler/HelpItem";
import { Controller, UseFormMethods } from "react-hook-form"; import { Controller, UseFormMethods, useWatch } from "react-hook-form";
import { FormAccess } from "../../components/form-access/FormAccess"; import { FormAccess } from "../../components/form-access/FormAccess";
import { WizardSectionHeader } from "../../components/wizard-section-header/WizardSectionHeader"; import { WizardSectionHeader } from "../../components/wizard-section-header/WizardSectionHeader";
import { PasswordInput } from "../../components/password-input/PasswordInput"; import { PasswordInput } from "../../components/password-input/PasswordInput";
import { useAdminClient } from "../../context/auth/AdminClient";
import { useRealm } from "../../context/realm-context/RealmContext";
import { useAlerts } from "../../components/alert/Alerts";
export type LdapSettingsConnectionProps = { export type LdapSettingsConnectionProps = {
form: UseFormMethods; form: UseFormMethods;
@ -21,13 +29,45 @@ export type LdapSettingsConnectionProps = {
showSectionDescription?: boolean; showSectionDescription?: boolean;
}; };
const testLdapProperties: Array<keyof TestLdapConnectionRepresentation> = [
"connectionUrl",
"bindDn",
"bindCredential",
"useTruststoreSpi",
"connectionTimeout",
"startTls",
"authType",
];
export const LdapSettingsConnection = ({ export const LdapSettingsConnection = ({
form, form,
showSectionHeading = false, showSectionHeading = false,
showSectionDescription = false, showSectionDescription = false,
}: LdapSettingsConnectionProps) => { }: LdapSettingsConnectionProps) => {
const { t } = useTranslation("user-federation"); const { t } = useTranslation("user-federation");
const helpText = useTranslation("user-federation-help").t; const { t: helpText } = useTranslation("user-federation-help");
const adminClient = useAdminClient();
const { realm } = useRealm();
const { addAlert } = useAlerts();
const testLdap = async () => {
try {
const settings: TestLdapConnectionRepresentation = {};
testLdapProperties.forEach((key) => {
const value = _.get(form.getValues(), `config.${key}`);
settings[key] = _.isArray(value) ? value[0] : "";
});
await adminClient.realms.testLDAPConnection(
{ realm },
{ ...settings, action: "testConnection" }
);
addAlert(t("testSuccess"), AlertVariant.success);
} catch (error) {
addAlert(t("testError"), AlertVariant.danger);
console.error(error.response?.data?.errorMessage);
}
};
const [ const [
isTruststoreSpiDropdownOpen, isTruststoreSpiDropdownOpen,
@ -36,6 +76,11 @@ export const LdapSettingsConnection = ({
const [isBindTypeDropdownOpen, setIsBindTypeDropdownOpen] = useState(false); const [isBindTypeDropdownOpen, setIsBindTypeDropdownOpen] = useState(false);
const ldapBindType = useWatch({
control: form.control,
name: "config.authType",
});
return ( return (
<> <>
{showSectionHeading && ( {showSectionHeading && (
@ -213,7 +258,7 @@ export const LdapSettingsConnection = ({
> >
<Controller <Controller
name="config.authType[0]" name="config.authType[0]"
defaultValue="" defaultValue="none"
control={form.control} control={form.control}
render={({ onChange, value }) => ( render={({ onChange, value }) => (
<Select <Select
@ -231,83 +276,81 @@ export const LdapSettingsConnection = ({
variant={SelectVariant.single} variant={SelectVariant.single}
data-testid="ldap-bind-type" data-testid="ldap-bind-type"
> >
<SelectOption key={3} value="simple" /> <SelectOption key={0} value="simple" />
<SelectOption key={4} value="none" /> <SelectOption key={1} value="none" isPlaceholder />
</Select> </Select>
)} )}
></Controller> ></Controller>
</FormGroup> </FormGroup>
<FormGroup
label={t("bindDn")} {_.isEqual(ldapBindType, ["simple"]) && (
labelIcon={ <>
<HelpItem <FormGroup
helpText={helpText("bindDnHelp")} label={t("bindDn")}
forLabel={t("bindDn")} labelIcon={
forID="kc-console-bind-dn" <HelpItem
/> helpText={helpText("bindDnHelp")}
} forLabel={t("bindDn")}
fieldId="kc-console-bind-dn" forID="kc-console-bind-dn"
isRequired />
> }
<TextInput fieldId="kc-console-bind-dn"
type="text" helperTextInvalid={t("validateBindDn")}
id="kc-console-bind-dn" validated={
data-testid="ldap-bind-dn" form.errors.config?.bindDn
name="config.bindDn[0]" ? ValidatedOptions.error
ref={form.register({ : ValidatedOptions.default
required: { }
value: true, isRequired
message: `${t("validateBindDn")}`, >
}, <TextInput
})} type="text"
/> id="kc-console-bind-dn"
{form.errors.config && data-testid="ldap-bind-dn"
form.errors.config.bindDn && name="config.bindDn[0]"
form.errors.config.bindDn[0] && ( ref={form.register({ required: true })}
<div className="error"> />
{form.errors.config.bindDn[0].message} </FormGroup>
</div> <FormGroup
)} label={t("bindCredentials")}
</FormGroup> labelIcon={
<FormGroup <HelpItem
label={t("bindCredentials")} helpText={helpText("bindCredentialsHelp")}
labelIcon={ forLabel={t("bindCredentials")}
<HelpItem forID="kc-console-bind-credentials"
helpText={helpText("bindCredentialsHelp")} />
forLabel={t("bindCredentials")} }
forID="kc-console-bind-credentials" fieldId="kc-console-bind-credentials"
/> helperTextInvalid={t("validateBindCredentials")}
} validated={
fieldId="kc-console-bind-credentials" form.errors.config?.bindCredential
isRequired ? ValidatedOptions.error
> : ValidatedOptions.default
<PasswordInput }
isRequired isRequired
id="kc-console-bind-credentials" >
data-testid="ldap-bind-credentials" <PasswordInput
name="config.bindCredential[0]" isRequired
ref={form.register({ id="kc-console-bind-credentials"
required: { data-testid="ldap-bind-credentials"
value: true, name="config.bindCredential[0]"
message: `${t("validateBindCredentials")}`, ref={form.register({
}, required: true,
})} })}
/> />
{form.errors.config && </FormGroup>
form.errors.config.bindCredential && <FormGroup fieldId="kc-test-button">
form.errors.config.bindCredential[0] && ( <Button
<div className="error"> isDisabled={!form.formState.isValid}
{form.errors.config.bindCredential[0].message} variant="secondary"
</div> id="kc-test-button"
)} onClick={() => testLdap()}
</FormGroup> >
<FormGroup fieldId="kc-test-button"> {t("common:test")}
{" "} </Button>
{/* TODO: whatever this button is supposed to do */} </FormGroup>
<Button variant="secondary" id="kc-test-button"> </>
{t("common:test")} )}
</Button>
</FormGroup>
</FormAccess> </FormAccess>
</> </>
); );

View file

@ -20,6 +20,9 @@ export const LdapSettingsSynchronization = ({
const { t } = useTranslation("user-federation"); const { t } = useTranslation("user-federation");
const helpText = useTranslation("user-federation-help").t; const helpText = useTranslation("user-federation-help").t;
const watchPeriodicSync = form.watch("config.periodicFullSync", false);
const watchChangedSync = form.watch("config.periodicChangedUsersSync", false);
return ( return (
<> <>
{showSectionHeading && ( {showSectionHeading && (
@ -78,50 +81,110 @@ export const LdapSettingsSynchronization = ({
ref={form.register} ref={form.register}
/> />
</FormGroup> </FormGroup>
{/* Enter -1 to switch off, otherwise enter value */}
<FormGroup <FormGroup
hasNoPaddingTop label={"Periodic full sync"}
label={t("fullSyncPeriod")}
labelIcon={ labelIcon={
<HelpItem <HelpItem
helpText={helpText("fullSyncPeriodHelp")} helpText={helpText("periodicFullSyncHelp")}
forLabel={t("fullSyncPeriod")} forLabel={"periodicFullSync"}
forID="kc-full-sync-period" forID="kc-periodic-full-sync"
/> />
} }
fieldId="kc-full-sync-period" fieldId="kc-periodic-full-sync"
>
<TextInput
type="number"
min={-1}
id="kc-full-sync-period"
name="config.fullSyncPeriod[0]"
ref={form.register}
/>
</FormGroup>
{/* Enter -1 to switch off, otherwise enter value */}
<FormGroup
label={t("changedUsersSyncPeriod")}
labelIcon={
<HelpItem
helpText={helpText("changedUsersSyncHelp")}
forLabel={t("changedUsersSyncPeriod")}
forID="kc-changed-users-sync-period"
/>
}
fieldId="kc-changed-users-sync-period"
hasNoPaddingTop hasNoPaddingTop
> >
<TextInput <Controller
type="number" name="config.periodicFullSync"
min={-1} defaultValue={false}
id="kc-changed-users-sync-period" control={form.control}
name="config.changedSyncPeriod[0]" render={({ onChange, value }) => (
ref={form.register} <Switch
/> id={"kc-periodic-full-sync"}
isDisabled={false}
onChange={(value) => onChange(value)}
isChecked={value === true}
label={t("common:on")}
labelOff={t("common:off")}
ref={form.register}
/>
)}
></Controller>
</FormGroup> </FormGroup>
{watchPeriodicSync && (
<FormGroup
hasNoPaddingTop
label={t("fullSyncPeriod")}
labelIcon={
<HelpItem
helpText={helpText("fullSyncPeriodHelp")}
forLabel={t("fullSyncPeriod")}
forID="kc-full-sync-period"
/>
}
fieldId="kc-full-sync-period"
>
<TextInput
type="number"
min={-1}
defaultValue={604800}
id="kc-full-sync-period"
name="config.fullSyncPeriod[0]"
ref={form.register}
/>
</FormGroup>
)}
<FormGroup
label={"Periodic Changed Users Sync"}
labelIcon={
<HelpItem
helpText={helpText("periodicChangedUsersSyncHelp")}
forLabel={"periodicChangedUsersSync"}
forID="kc-periodic-changed-users-sync"
/>
}
fieldId="kc-periodic-changed-users-sync"
hasNoPaddingTop
>
<Controller
name="config.periodicChangedUsersSync"
defaultValue={false}
control={form.control}
render={({ onChange, value }) => (
<Switch
id={"kc-periodic-changed-users-sync"}
isDisabled={false}
onChange={(value) => onChange(value)}
isChecked={value === true}
label={t("common:on")}
labelOff={t("common:off")}
ref={form.register}
/>
)}
></Controller>
</FormGroup>
{watchChangedSync && (
<FormGroup
label={t("changedUsersSyncPeriod")}
labelIcon={
<HelpItem
helpText={helpText("changedUsersSyncHelp")}
forLabel={t("changedUsersSyncPeriod")}
forID="kc-changed-users-sync-period"
/>
}
fieldId="kc-changed-users-sync-period"
hasNoPaddingTop
>
<TextInput
type="number"
min={-1}
defaultValue={86400}
id="kc-changed-users-sync-period"
name="config.changedSyncPeriod[0]"
ref={form.register}
/>
</FormGroup>
)}
</FormAccess> </FormAccess>
</> </>
); );

View file

@ -81,9 +81,11 @@
"subtree": "Subtree", "subtree": "Subtree",
"saveSuccess": "User federation provider successfully saved", "saveSuccess": "User federation provider successfully saved",
"saveError": "User federation provider could not be saved: {error}", "saveError": "User federation provider could not be saved: {{error}}",
"createSuccess": "User federation provider successfully created", "createSuccess": "User federation provider successfully created",
"createError": "User federation provider could not be created: {error}", "createError": "User federation provider could not be created: {{error}}",
"testSuccess": "Successfully connected to LDAP",
"testError": "Error when trying to connect to LDAP. See server.log for details.",
"learnMore": "Learn more", "learnMore": "Learn more",
"addNewProvider": "Add new provider", "addNewProvider": "Add new provider",