Use React Router v6 for the routable tabs of the user federation LDAP settings page (#4126)

This commit is contained in:
Jon Koops 2023-01-05 12:38:16 +01:00 committed by GitHub
parent b509a5a04e
commit d2163efe3f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 239 additions and 181 deletions

View file

@ -0,0 +1,49 @@
import { AlertVariant, PageSection } from "@patternfly/react-core";
import { FormProvider, useForm } from "react-hook-form";
import { useTranslation } from "react-i18next";
import { useNavigate } from "react-router-dom-v5-compat";
import { useAlerts } from "../components/alert/Alerts";
import { useAdminClient } from "../context/auth/AdminClient";
import { useRealm } from "../context/realm-context/RealmContext";
import { toUserFederation } from "./routes/UserFederation";
import { ExtendedHeader } from "./shared/ExtendedHeader";
import {
LdapComponentRepresentation,
serializeFormData,
UserFederationLdapForm,
} from "./UserFederationLdapForm";
export default function CreateUserFederationLdapSettings() {
const { t } = useTranslation("user-federation");
const form = useForm<LdapComponentRepresentation>({ mode: "onChange" });
const navigate = useNavigate();
const { adminClient } = useAdminClient();
const { realm } = useRealm();
const { addAlert, addError } = useAlerts();
const onSubmit = async (formData: LdapComponentRepresentation) => {
try {
await adminClient.components.create(serializeFormData(formData));
addAlert(t("createSuccess"), AlertVariant.success);
navigate(toUserFederation({ realm }));
} catch (error) {
addError("user-federation:createError", error);
}
};
return (
<FormProvider {...form}>
<ExtendedHeader
provider="LDAP"
noDivider
save={() => form.handleSubmit(onSubmit)()}
/>
<PageSection variant="light" className="pf-u-p-0">
<PageSection variant="light">
<UserFederationLdapForm onSubmit={onSubmit} />
</PageSection>
</PageSection>
</FormProvider>
);
}

View file

@ -0,0 +1,113 @@
import type ComponentRepresentation from "@keycloak/keycloak-admin-client/lib/defs/componentRepresentation";
import { ActionGroup, Button, Form } from "@patternfly/react-core";
import { useFormContext } from "react-hook-form";
import { useTranslation } from "react-i18next";
import { useNavigate } from "react-router-dom-v5-compat";
import { ScrollForm } from "../components/scroll-form/ScrollForm";
import { useRealm } from "../context/realm-context/RealmContext";
import { LdapSettingsAdvanced } from "./ldap/LdapSettingsAdvanced";
import { LdapSettingsConnection } from "./ldap/LdapSettingsConnection";
import { LdapSettingsGeneral } from "./ldap/LdapSettingsGeneral";
import { LdapSettingsKerberosIntegration } from "./ldap/LdapSettingsKerberosIntegration";
import { LdapSettingsSearching } from "./ldap/LdapSettingsSearching";
import { LdapSettingsSynchronization } from "./ldap/LdapSettingsSynchronization";
import { toUserFederation } from "./routes/UserFederation";
import { SettingsCache } from "./shared/SettingsCache";
export type LdapComponentRepresentation = ComponentRepresentation & {
config?: {
periodicChangedUsersSync?: boolean;
periodicFullSync?: boolean;
};
};
export type UserFederationLdapFormProps = {
id?: string;
onSubmit: (formData: LdapComponentRepresentation) => void;
};
export const UserFederationLdapForm = ({
id,
onSubmit,
}: UserFederationLdapFormProps) => {
const { t } = useTranslation("user-federation");
const form = useFormContext<LdapComponentRepresentation>();
const navigate = useNavigate();
const { realm } = useRealm();
return (
<>
<ScrollForm
sections={[
{
title: t("generalOptions"),
panel: <LdapSettingsGeneral form={form} vendorEdit={!!id} />,
},
{
title: t("connectionAndAuthenticationSettings"),
panel: <LdapSettingsConnection form={form} id={id} />,
},
{
title: t("ldapSearchingAndUpdatingSettings"),
panel: <LdapSettingsSearching form={form} />,
},
{
title: t("synchronizationSettings"),
panel: <LdapSettingsSynchronization form={form} />,
},
{
title: t("kerberosIntegration"),
panel: <LdapSettingsKerberosIntegration form={form} />,
},
{ title: t("cacheSettings"), panel: <SettingsCache form={form} /> },
{
title: t("advancedSettings"),
panel: <LdapSettingsAdvanced form={form} id={id} />,
},
]}
/>
<Form onSubmit={form.handleSubmit(onSubmit)}>
<ActionGroup className="keycloak__form_actions">
<Button
isDisabled={!form.formState.isDirty}
variant="primary"
type="submit"
data-testid="ldap-save"
>
{t("common:save")}
</Button>
<Button
variant="link"
onClick={() => navigate(toUserFederation({ realm }))}
data-testid="ldap-cancel"
>
{t("common:cancel")}
</Button>
</ActionGroup>
</Form>
</>
);
};
export function serializeFormData(
formData: LdapComponentRepresentation
): LdapComponentRepresentation {
const { config } = formData;
if (config?.periodicChangedUsersSync !== undefined) {
if (config.periodicChangedUsersSync === false) {
config.changedSyncPeriod = ["-1"];
}
delete config.periodicChangedUsersSync;
}
if (config?.periodicFullSync !== undefined) {
if (config.periodicFullSync === false) {
config.fullSyncPeriod = ["-1"];
}
delete config.periodicFullSync;
}
return formData;
}

View file

@ -1,151 +1,69 @@
import { useState } from "react"; import type ComponentRepresentation from "@keycloak/keycloak-admin-client/lib/defs/componentRepresentation";
import { import {
ActionGroup,
AlertVariant, AlertVariant,
Button,
Form,
PageSection, PageSection,
Tab, Tab,
TabTitleText, TabTitleText,
} from "@patternfly/react-core"; } from "@patternfly/react-core";
import { useState } from "react";
import { LdapSettingsAdvanced } from "./ldap/LdapSettingsAdvanced"; import { FormProvider, useForm } from "react-hook-form";
import { LdapSettingsKerberosIntegration } from "./ldap/LdapSettingsKerberosIntegration";
import { SettingsCache } from "./shared/SettingsCache";
import { LdapSettingsSynchronization } from "./ldap/LdapSettingsSynchronization";
import { LdapSettingsGeneral } from "./ldap/LdapSettingsGeneral";
import { LdapSettingsConnection } from "./ldap/LdapSettingsConnection";
import { LdapSettingsSearching } from "./ldap/LdapSettingsSearching";
import { useRealm } from "../context/realm-context/RealmContext";
import type ComponentRepresentation from "@keycloak/keycloak-admin-client/lib/defs/componentRepresentation";
import { FormProvider, useForm, useFormContext } from "react-hook-form";
import { useAdminClient, useFetch } from "../context/auth/AdminClient";
import { useAlerts } from "../components/alert/Alerts";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { useHistory } from "react-router-dom"; import { useParams } from "react-router-dom-v5-compat";
import { useNavigate, useParams } from "react-router-dom-v5-compat";
import { ScrollForm } from "../components/scroll-form/ScrollForm";
import { useAlerts } from "../components/alert/Alerts";
import { KeycloakSpinner } from "../components/keycloak-spinner/KeycloakSpinner";
import {
RoutableTabs,
useRoutableTab,
} from "../components/routable-tabs/RoutableTabs";
import { useAdminClient, useFetch } from "../context/auth/AdminClient";
import { useRealm } from "../context/realm-context/RealmContext";
import { LdapMapperList } from "./ldap/mappers/LdapMapperList"; import { LdapMapperList } from "./ldap/mappers/LdapMapperList";
import { toUserFederation } from "./routes/UserFederation"; import {
toUserFederationLdap,
UserFederationLdapParams,
UserFederationLdapTab,
} from "./routes/UserFederationLdap";
import { ExtendedHeader } from "./shared/ExtendedHeader"; import { ExtendedHeader } from "./shared/ExtendedHeader";
import { import {
routableTab, LdapComponentRepresentation,
RoutableTabs, serializeFormData,
} from "../components/routable-tabs/RoutableTabs"; UserFederationLdapForm,
import { toUserFederationLdap } from "./routes/UserFederationLdap"; } from "./UserFederationLdapForm";
type ldapComponentRepresentation = ComponentRepresentation & {
config?: {
periodicChangedUsersSync?: boolean;
periodicFullSync?: boolean;
};
};
const AddLdapFormContent = ({
save,
}: {
save: (component: ldapComponentRepresentation) => void;
}) => {
const { t } = useTranslation("user-federation");
const form = useFormContext();
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const { realm } = useRealm();
return (
<>
<ScrollForm
sections={[
{
title: t("generalOptions"),
panel: <LdapSettingsGeneral form={form} vendorEdit={!!id} />,
},
{
title: t("connectionAndAuthenticationSettings"),
panel: <LdapSettingsConnection form={form} id={id} />,
},
{
title: t("ldapSearchingAndUpdatingSettings"),
panel: <LdapSettingsSearching form={form} />,
},
{
title: t("synchronizationSettings"),
panel: <LdapSettingsSynchronization form={form} />,
},
{
title: t("kerberosIntegration"),
panel: <LdapSettingsKerberosIntegration form={form} />,
},
{ title: t("cacheSettings"), panel: <SettingsCache form={form} /> },
{
title: t("advancedSettings"),
panel: <LdapSettingsAdvanced form={form} id={id} />,
},
]}
/>
<Form onSubmit={form.handleSubmit(save)}>
<ActionGroup className="keycloak__form_actions">
<Button
isDisabled={!form.formState.isDirty}
variant="primary"
type="submit"
data-testid="ldap-save"
>
{t("common:save")}
</Button>
<Button
variant="link"
onClick={() => navigate(toUserFederation({ realm }))}
data-testid="ldap-cancel"
>
{t("common:cancel")}
</Button>
</ActionGroup>
</Form>
</>
);
};
export default function UserFederationLdapSettings() { export default function UserFederationLdapSettings() {
const { t } = useTranslation("user-federation"); const { t } = useTranslation("user-federation");
const form = useForm<ComponentRepresentation>({ mode: "onChange" }); const form = useForm<LdapComponentRepresentation>({ mode: "onChange" });
const navigate = useNavigate();
const history = useHistory();
const { adminClient } = useAdminClient(); const { adminClient } = useAdminClient();
const { realm } = useRealm(); const { realm } = useRealm();
const { id } = useParams<UserFederationLdapParams>();
const { id } = useParams<{ id: string }>();
const { addAlert, addError } = useAlerts(); const { addAlert, addError } = useAlerts();
const [component, setComponent] = useState<ComponentRepresentation>(); const [component, setComponent] = useState<ComponentRepresentation>();
const [refreshCount, setRefreshCount] = useState(0); const [refreshCount, setRefreshCount] = useState(0);
const editMode = component?.config?.editMode;
const refresh = () => setRefreshCount((count) => count + 1); const refresh = () => setRefreshCount((count) => count + 1);
useFetch( useFetch(
async () => { () => adminClient.components.findOne({ id: id! }),
if (id) { (component) => {
return await adminClient.components.findOne({ id }); if (!component) {
}
return undefined;
},
(fetchedComponent) => {
if (fetchedComponent) {
setupForm(fetchedComponent);
setComponent(fetchedComponent);
} else if (id) {
throw new Error(t("common:notFound")); throw new Error(t("common:notFound"));
} }
setComponent(component);
setupForm(component);
}, },
[refreshCount] [id, refreshCount]
); );
const useTab = (tab: UserFederationLdapTab) =>
useRoutableTab(toUserFederationLdap({ realm, id: id!, tab }));
const settingsTab = useTab("settings");
const mappersTab = useTab("mappers");
const setupForm = (component: ComponentRepresentation) => { const setupForm = (component: ComponentRepresentation) => {
form.reset({ ...component }); form.reset(component);
form.setValue( form.setValue(
"config.periodicChangedUsersSync", "config.periodicChangedUsersSync",
component.config?.["changedSyncPeriod"]?.[0] !== "-1" component.config?.["changedSyncPeriod"]?.[0] !== "-1"
@ -157,80 +75,58 @@ export default function UserFederationLdapSettings() {
); );
}; };
const save = async (component: ldapComponentRepresentation) => { const onSubmit = async (formData: LdapComponentRepresentation) => {
if (component.config?.periodicChangedUsersSync !== undefined) {
if (component.config.periodicChangedUsersSync === false) {
component.config.changedSyncPeriod = ["-1"];
}
delete component.config.periodicChangedUsersSync;
}
if (component.config?.periodicFullSync !== undefined) {
if (component.config.periodicFullSync === false) {
component.config.fullSyncPeriod = ["-1"];
}
delete component.config.periodicFullSync;
}
try { try {
if (!id) { await adminClient.components.update(
await adminClient.components.create(component); { id: id! },
navigate(toUserFederation({ realm })); serializeFormData(formData)
} else { );
await adminClient.components.update({ id }, component); addAlert(t("saveSuccess"), AlertVariant.success);
}
addAlert(t(id ? "saveSuccess" : "createSuccess"), AlertVariant.success);
refresh(); refresh();
} catch (error) { } catch (error) {
addError(`user-federation:${id ? "saveError" : "createError"}`, error); addError("user-federation:saveError", error);
} }
}; };
if (!component) {
return <KeycloakSpinner />;
}
return ( return (
<FormProvider {...form}> <FormProvider {...form}>
<ExtendedHeader <ExtendedHeader
provider="LDAP" provider="LDAP"
noDivider noDivider
editMode={editMode} editMode={component.config?.editMode}
save={() => form.handleSubmit(save)()} save={() => form.handleSubmit(onSubmit)()}
/> />
<PageSection variant="light" className="pf-u-p-0"> <PageSection variant="light" className="pf-u-p-0">
{id ? ( <RoutableTabs
<RoutableTabs defaultLocation={toUserFederationLdap({
defaultLocation={toUserFederationLdap({ realm,
realm, id: id!,
id, tab: "settings",
tab: "settings", })}
})} isBox
isBox >
<Tab
id="settings"
title={<TabTitleText>{t("common:settings")}</TabTitleText>}
{...settingsTab}
> >
<Tab <PageSection variant="light">
id="settings" <UserFederationLdapForm id={id} onSubmit={onSubmit} />
title={<TabTitleText>{t("common:settings")}</TabTitleText>} </PageSection>
{...routableTab({ </Tab>
to: toUserFederationLdap({ realm, id, tab: "settings" }), <Tab
history, id="mappers"
})} title={<TabTitleText>{t("common:mappers")}</TabTitleText>}
> data-testid="ldap-mappers-tab"
<PageSection variant="light"> {...mappersTab}
<AddLdapFormContent save={save} /> >
</PageSection> <LdapMapperList />
</Tab> </Tab>
<Tab </RoutableTabs>
id="mappers"
title={<TabTitleText>{t("common:mappers")}</TabTitleText>}
data-testid="ldap-mappers-tab"
{...routableTab({
to: toUserFederationLdap({ realm, id, tab: "mappers" }),
history,
})}
>
<LdapMapperList />
</Tab>
</RoutableTabs>
) : (
<PageSection variant="light">
<AddLdapFormContent save={save} />
</PageSection>
)}
</PageSection> </PageSection>
</FormProvider> </FormProvider>
); );

View file

@ -7,7 +7,7 @@ export type NewLdapUserFederationParams = { realm: string };
export const NewLdapUserFederationRoute: RouteDef = { export const NewLdapUserFederationRoute: RouteDef = {
path: "/:realm/user-federation/ldap/new", path: "/:realm/user-federation/ldap/new",
component: lazy(() => import("../UserFederationLdapSettings")), component: lazy(() => import("../CreateUserFederationLdapSettings")),
breadcrumb: (t) => breadcrumb: (t) =>
t("user-federation:addProvider", { provider: "LDAP", count: 1 }), t("user-federation:addProvider", { provider: "LDAP", count: 1 }),
access: "view-realm", access: "view-realm",

View file

@ -3,7 +3,7 @@ import type { Path } from "react-router-dom-v5-compat";
import { generatePath } from "react-router-dom-v5-compat"; import { generatePath } from "react-router-dom-v5-compat";
import type { RouteDef } from "../../route-config"; import type { RouteDef } from "../../route-config";
type UserFederationLdapTab = "settings" | "mappers"; export type UserFederationLdapTab = "settings" | "mappers";
export type UserFederationLdapParams = { export type UserFederationLdapParams = {
realm: string; realm: string;