only query realm once (#563)

fixing: #548
This commit is contained in:
Erik Jan de Wit 2021-04-30 21:08:12 +02:00 committed by GitHub
parent ffbeddebe7
commit e1d53c640e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 104 additions and 230 deletions

View file

@ -1,10 +1,8 @@
import React, { useEffect, useState } from "react"; import React, { useState } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { Controller, useForm } from "react-hook-form"; import { Controller, useFormContext } from "react-hook-form";
import { useErrorHandler } from "react-error-boundary";
import { import {
ActionGroup, ActionGroup,
AlertVariant,
Button, Button,
ClipboardCopy, ClipboardCopy,
FormGroup, FormGroup,
@ -20,52 +18,31 @@ import {
import RealmRepresentation from "keycloak-admin/lib/defs/realmRepresentation"; import RealmRepresentation from "keycloak-admin/lib/defs/realmRepresentation";
import { getBaseUrl } from "../util"; import { getBaseUrl } from "../util";
import { useAdminClient, asyncStateFetch } from "../context/auth/AdminClient"; import { useAdminClient } from "../context/auth/AdminClient";
import { useRealm } from "../context/realm-context/RealmContext"; import { useRealm } from "../context/realm-context/RealmContext";
import { useAlerts } from "../components/alert/Alerts";
import { FormAccess } from "../components/form-access/FormAccess"; import { FormAccess } from "../components/form-access/FormAccess";
import { HelpItem } from "../components/help-enabler/HelpItem"; import { HelpItem } from "../components/help-enabler/HelpItem";
import { FormattedLink } from "../components/external-link/FormattedLink"; import { FormattedLink } from "../components/external-link/FormattedLink";
export const RealmSettingsGeneralTab = () => { type RealmSettingsGeneralTabProps = {
save: (realm: RealmRepresentation) => void;
reset: () => void;
};
export const RealmSettingsGeneralTab = ({
save,
reset,
}: RealmSettingsGeneralTabProps) => {
const { t } = useTranslation("realm-settings"); const { t } = useTranslation("realm-settings");
const adminClient = useAdminClient(); const adminClient = useAdminClient();
const handleError = useErrorHandler();
const { realm: realmName } = useRealm(); const { realm: realmName } = useRealm();
const { addAlert } = useAlerts(); const { register, control, handleSubmit } = useFormContext();
const { register, control, setValue, handleSubmit } = useForm();
const [realm, setRealm] = useState<RealmRepresentation>();
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
const baseUrl = getBaseUrl(adminClient); const baseUrl = getBaseUrl(adminClient);
const requireSslTypes = ["all", "external", "none"]; const requireSslTypes = ["all", "external", "none"];
useEffect(() => {
return asyncStateFetch(
() => adminClient.realms.findOne({ realm: realmName }),
(realm) => {
setRealm(realm);
setupForm(realm);
},
handleError
);
}, []);
const setupForm = (realm: RealmRepresentation) => {
Object.entries(realm).map((entry) => setValue(entry[0], entry[1]));
};
const save = async (realm: RealmRepresentation) => {
try {
await adminClient.realms.update({ realm: realmName }, realm);
setRealm(realm);
addAlert(t("saveSuccess"), AlertVariant.success);
} catch (error) {
addAlert(t("saveError", { error }), AlertVariant.danger);
}
};
return ( return (
<> <>
<PageSection variant="light"> <PageSection variant="light">
@ -219,7 +196,7 @@ export const RealmSettingsGeneralTab = () => {
> >
{t("common:save")} {t("common:save")}
</Button> </Button>
<Button variant="link" onClick={() => setupForm(realm!)}> <Button variant="link" onClick={reset}>
{t("common:revert")} {t("common:revert")}
</Button> </Button>
</ActionGroup> </ActionGroup>

View file

@ -1,48 +1,22 @@
import React, { useEffect, useState } from "react"; import React from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { import { FormGroup, PageSection, Switch } from "@patternfly/react-core";
AlertVariant,
FormGroup,
PageSection,
Switch,
} from "@patternfly/react-core";
import { FormAccess } from "../components/form-access/FormAccess"; import { FormAccess } from "../components/form-access/FormAccess";
import { HelpItem } from "../components/help-enabler/HelpItem"; import { HelpItem } from "../components/help-enabler/HelpItem";
import { FormPanel } from "../components/scroll-form/FormPanel"; import { FormPanel } from "../components/scroll-form/FormPanel";
import { asyncStateFetch, useAdminClient } from "../context/auth/AdminClient";
import RealmRepresentation from "keycloak-admin/lib/defs/realmRepresentation"; import RealmRepresentation from "keycloak-admin/lib/defs/realmRepresentation";
import { useErrorHandler } from "react-error-boundary";
import { useRealm } from "../context/realm-context/RealmContext";
import { useAlerts } from "../components/alert/Alerts";
export const RealmSettingsLoginTab = () => { type RealmSettingsLoginTabProps = {
const { t } = useTranslation("realm-settings"); save: (realm: RealmRepresentation) => void;
const [realm, setRealm] = useState<RealmRepresentation>(); realm: RealmRepresentation;
const handleError = useErrorHandler();
const adminClient = useAdminClient();
const { realm: realmName } = useRealm();
const { addAlert } = useAlerts();
useEffect(() => {
return asyncStateFetch(
() => adminClient.realms.findOne({ realm: realmName }),
(realm) => {
setRealm(realm);
},
handleError
);
}, []);
const save = async (realm: RealmRepresentation) => {
try {
await adminClient.realms.update({ realm: realmName }, realm);
setRealm(realm);
addAlert(t("saveSuccess"), AlertVariant.success);
} catch (error) {
addAlert(t("saveError", { error }), AlertVariant.danger);
}
}; };
export const RealmSettingsLoginTab = ({
save,
realm,
}: RealmSettingsLoginTabProps) => {
const { t } = useTranslation("realm-settings");
return ( return (
<> <>
<PageSection variant="light"> <PageSection variant="light">

View file

@ -1,7 +1,7 @@
import React, { useEffect, useState } from "react"; import React, { useEffect, useState } from "react";
import { useHistory } from "react-router-dom"; import { useHistory } from "react-router-dom";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { Controller, useForm } from "react-hook-form"; import { Controller, FormProvider, useForm } from "react-hook-form";
import { useErrorHandler } from "react-error-boundary"; import { useErrorHandler } from "react-error-boundary";
import { import {
AlertVariant, AlertVariant,
@ -122,13 +122,16 @@ export const RealmSettingsSection = () => {
const handleError = useErrorHandler(); const handleError = useErrorHandler();
const { realm: realmName } = useRealm(); const { realm: realmName } = useRealm();
const { addAlert } = useAlerts(); const { addAlert } = useAlerts();
const { control, getValues, setValue } = useForm(); const form = useForm();
const { control, getValues, setValue } = form;
const [realm, setRealm] = useState<RealmRepresentation>();
useEffect(() => { useEffect(() => {
return asyncStateFetch( return asyncStateFetch(
() => adminClient.realms.findOne({ realm: realmName }), () => adminClient.realms.findOne({ realm: realmName }),
(realm) => { (realm) => {
setupForm(realm); setupForm(realm);
setRealm(realm);
}, },
handleError handleError
); );
@ -141,6 +144,7 @@ export const RealmSettingsSection = () => {
const save = async (realm: RealmRepresentation) => { const save = async (realm: RealmRepresentation) => {
try { try {
await adminClient.realms.update({ realm: realmName }, realm); await adminClient.realms.update({ realm: realmName }, realm);
setRealm(realm);
addAlert(t("saveSuccess"), AlertVariant.success); addAlert(t("saveSuccess"), AlertVariant.success);
} catch (error) { } catch (error) {
addAlert(t("saveError", { error }), AlertVariant.danger); addAlert(t("saveError", { error }), AlertVariant.danger);
@ -163,29 +167,37 @@ export const RealmSettingsSection = () => {
)} )}
/> />
<PageSection variant="light" className="pf-u-p-0"> <PageSection variant="light" className="pf-u-p-0">
<FormProvider {...form}>
<KeycloakTabs isBox> <KeycloakTabs isBox>
<Tab <Tab
eventKey="general" eventKey="general"
title={<TabTitleText>{t("realm-settings:general")}</TabTitleText>} title={<TabTitleText>{t("realm-settings:general")}</TabTitleText>}
data-testid="rs-general-tab" data-testid="rs-general-tab"
> >
<RealmSettingsGeneralTab /> <RealmSettingsGeneralTab
save={save}
reset={() => setupForm(realm!)}
/>
</Tab> </Tab>
<Tab <Tab
eventKey="login" eventKey="login"
title={<TabTitleText>{t("realm-settings:login")}</TabTitleText>} title={<TabTitleText>{t("realm-settings:login")}</TabTitleText>}
data-testid="rs-login-tab" data-testid="rs-login-tab"
> >
<RealmSettingsLoginTab /> <RealmSettingsLoginTab save={save} realm={realm!} />
</Tab> </Tab>
<Tab <Tab
eventKey="themes" eventKey="themes"
title={<TabTitleText>{t("realm-settings:themes")}</TabTitleText>} title={<TabTitleText>{t("realm-settings:themes")}</TabTitleText>}
data-testid="rs-themes-tab" data-testid="rs-themes-tab"
> >
<RealmSettingsThemesTab /> <RealmSettingsThemesTab
save={save}
reset={() => setupForm(realm!)}
/>
</Tab> </Tab>
</KeycloakTabs> </KeycloakTabs>
</FormProvider>
</PageSection> </PageSection>
</> </>
); );

View file

@ -1,31 +0,0 @@
import React from "react";
import { PageSection, Tab, TabTitleText } from "@patternfly/react-core";
import { useTranslation } from "react-i18next";
import { KeycloakTabs } from "../components/keycloak-tabs/KeycloakTabs";
import { RealmSettingsLoginTab } from "./LoginTab";
import { RealmSettingsGeneralTab } from "./GeneralTab";
export const RealmSettingsTabs = () => {
const { t } = useTranslation("roles");
return (
<>
<PageSection variant="light" className="pf-u-p-0">
<KeycloakTabs isBox>
<Tab
eventKey="general"
title={<TabTitleText>{t("realm-settings:general")}</TabTitleText>}
>
<RealmSettingsGeneralTab />
</Tab>
<Tab
eventKey="login"
title={<TabTitleText>{t("realm-settings:login")}</TabTitleText>}
>
<RealmSettingsLoginTab />
</Tab>
</KeycloakTabs>
</PageSection>
</>
);
};

View file

@ -1,10 +1,8 @@
import React, { useEffect, useState } from "react"; import React, { useState } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { Controller, useForm } from "react-hook-form"; import { Controller, useFormContext, useWatch } from "react-hook-form";
import { useErrorHandler } from "react-error-boundary";
import { import {
ActionGroup, ActionGroup,
AlertVariant,
Button, Button,
FormGroup, FormGroup,
PageSection, PageSection,
@ -15,21 +13,20 @@ import {
} from "@patternfly/react-core"; } from "@patternfly/react-core";
import RealmRepresentation from "keycloak-admin/lib/defs/realmRepresentation"; import RealmRepresentation from "keycloak-admin/lib/defs/realmRepresentation";
import { useAdminClient, asyncStateFetch } from "../context/auth/AdminClient";
import { useRealm } from "../context/realm-context/RealmContext";
import { useAlerts } from "../components/alert/Alerts";
import { FormAccess } from "../components/form-access/FormAccess"; import { FormAccess } from "../components/form-access/FormAccess";
import { HelpItem } from "../components/help-enabler/HelpItem"; import { HelpItem } from "../components/help-enabler/HelpItem";
import { useServerInfo } from "../context/server-info/ServerInfoProvider"; import { useServerInfo } from "../context/server-info/ServerInfoProvider";
export const RealmSettingsThemesTab = () => { type RealmSettingsThemesTabProps = {
save: (realm: RealmRepresentation) => void;
reset: () => void;
};
export const RealmSettingsThemesTab = ({
save,
reset,
}: RealmSettingsThemesTabProps) => {
const { t } = useTranslation("realm-settings"); const { t } = useTranslation("realm-settings");
const adminClient = useAdminClient();
const handleError = useErrorHandler();
const { realm: realmName } = useRealm();
const { addAlert } = useAlerts();
const { control, setValue, handleSubmit } = useForm();
const [realm, setRealm] = useState<RealmRepresentation>();
const [loginThemeOpen, setLoginThemeOpen] = useState(false); const [loginThemeOpen, setLoginThemeOpen] = useState(false);
const [accountThemeOpen, setAccountThemeOpen] = useState(false); const [accountThemeOpen, setAccountThemeOpen] = useState(false);
@ -38,60 +35,22 @@ export const RealmSettingsThemesTab = () => {
const [supportedLocalesOpen, setSupportedLocalesOpen] = useState(false); const [supportedLocalesOpen, setSupportedLocalesOpen] = useState(false);
const [defaultLocaleOpen, setDefaultLocaleOpen] = useState(false); const [defaultLocaleOpen, setDefaultLocaleOpen] = useState(false);
const [selections, setSelections] = useState<string[]>([]);
const [ const { control, handleSubmit } = useFormContext();
internationalizationEnabled,
setInternationalizationEnabled,
] = useState(false);
const form = useForm();
const themeTypes = useServerInfo().themes!; const themeTypes = useServerInfo().themes!;
const watchSupportedLocales = form.watch( const watchSupportedLocales = useWatch({
"supportedLocales", control,
themeTypes?.account![0].locales name: "supportedLocales",
); defaultValue: themeTypes?.account![0].locales,
useEffect(() => {
return asyncStateFetch(
() => adminClient.realms.findOne({ realm: realmName }),
(realm) => {
setRealm(realm);
setupForm(realm);
setInternationalizationEnabled(realm.internationalizationEnabled!);
},
handleError
);
}, []);
useEffect(() => {
setValue("supportedLocales", realm?.supportedLocales);
setValue("defaultLocale", realm?.defaultLocale);
}, [internationalizationEnabled]);
const setupForm = (realm: RealmRepresentation) => {
const { ...formValues } = realm;
form.reset(formValues);
Object.entries(realm).map((entry) => {
if (entry[0] === "internationalizationEnabled") {
setInternationalizationEnabled(realm!.internationalizationEnabled!);
}
setValue(entry[0], entry[1]);
}); });
};
const save = async (realm: RealmRepresentation) => { const internationalizationEnabled = useWatch({
try { control,
await adminClient.realms.update({ realm: realmName }, realm); name: "internationalizationEnabled",
setRealm({ supportedLocales: selections, ...realm }); defaultValue: false,
addAlert(t("saveSuccess"), AlertVariant.success); });
} catch (error) {
addAlert(t("saveError", { error }), AlertVariant.danger);
}
};
return ( return (
<> <>
@ -116,6 +75,7 @@ export const RealmSettingsThemesTab = () => {
<Controller <Controller
name="loginTheme" name="loginTheme"
control={control} control={control}
defaultValue=""
render={({ onChange, value }) => ( render={({ onChange, value }) => (
<Select <Select
toggleId="kc-login-theme" toggleId="kc-login-theme"
@ -158,6 +118,7 @@ export const RealmSettingsThemesTab = () => {
<Controller <Controller
name="accountTheme" name="accountTheme"
control={control} control={control}
defaultValue=""
render={({ onChange, value }) => ( render={({ onChange, value }) => (
<Select <Select
toggleId="kc-account-theme" toggleId="kc-account-theme"
@ -200,6 +161,7 @@ export const RealmSettingsThemesTab = () => {
<Controller <Controller
name="adminTheme" name="adminTheme"
control={control} control={control}
defaultValue=""
render={({ onChange, value }) => ( render={({ onChange, value }) => (
<Select <Select
toggleId="kc-admin-console-theme" toggleId="kc-admin-console-theme"
@ -244,6 +206,7 @@ export const RealmSettingsThemesTab = () => {
<Controller <Controller
name="emailTheme" name="emailTheme"
control={control} control={control}
defaultValue=""
render={({ onChange, value }) => ( render={({ onChange, value }) => (
<Select <Select
toggleId="kc-email-theme" toggleId="kc-email-theme"
@ -279,6 +242,7 @@ export const RealmSettingsThemesTab = () => {
<Controller <Controller
name="internationalizationEnabled" name="internationalizationEnabled"
control={control} control={control}
defaultValue={false}
render={({ onChange, value }) => ( render={({ onChange, value }) => (
<Switch <Switch
id="kc-internationalization" id="kc-internationalization"
@ -290,14 +254,7 @@ export const RealmSettingsThemesTab = () => {
? "internationalization-enabled" ? "internationalization-enabled"
: "internationalization-disabled" : "internationalization-disabled"
} }
onChange={(value) => { onChange={onChange}
onChange(value);
if (value) {
setValue("internationalizationEnabled", true);
setInternationalizationEnabled(value);
}
setInternationalizationEnabled(value);
}}
/> />
)} )}
/> />
@ -311,6 +268,7 @@ export const RealmSettingsThemesTab = () => {
<Controller <Controller
name="supportedLocales" name="supportedLocales"
control={control} control={control}
defaultValue={themeTypes?.account![0].locales}
render={({ value, onChange }) => ( render={({ value, onChange }) => (
<Select <Select
toggleId="kc-supported-locales" toggleId="kc-supported-locales"
@ -330,10 +288,9 @@ export const RealmSettingsThemesTab = () => {
onChange([...value, option]); onChange([...value, option]);
setSupportedLocalesOpen(false); setSupportedLocalesOpen(false);
} }
setSelections([...value, v]);
}} }}
onClear={() => { onClear={() => {
onChange(setSelections([])); onChange([]);
}} }}
selections={value} selections={value}
variant={SelectVariant.typeaheadMulti} variant={SelectVariant.typeaheadMulti}
@ -360,6 +317,7 @@ export const RealmSettingsThemesTab = () => {
<Controller <Controller
name="defaultLocale" name="defaultLocale"
control={control} control={control}
defaultValue=""
render={({ onChange, value }) => ( render={({ onChange, value }) => (
<Select <Select
toggleId="kc-default-locale" toggleId="kc-default-locale"
@ -375,16 +333,7 @@ export const RealmSettingsThemesTab = () => {
placeholderText="Select one" placeholderText="Select one"
data-testid="select-default-locale" data-testid="select-default-locale"
> >
{selections.length !== 0 {watchSupportedLocales.map(
? selections.map((locale: string, idx: number) => (
<SelectOption
key={`default-locale-${idx}`}
value={locale}
>
{t(`allSupportedLocales.${locale}`)}
</SelectOption>
))
: watchSupportedLocales.map(
(locale: string, idx: number) => ( (locale: string, idx: number) => (
<SelectOption <SelectOption
key={`default-locale-${idx}`} key={`default-locale-${idx}`}
@ -408,7 +357,7 @@ export const RealmSettingsThemesTab = () => {
> >
{t("common:save")} {t("common:save")}
</Button> </Button>
<Button variant="link" onClick={() => setupForm(realm!)}> <Button variant="link" onClick={reset}>
{t("common:revert")} {t("common:revert")}
</Button> </Button>
</ActionGroup> </ActionGroup>

View file

@ -29,7 +29,6 @@ import { RoleMappingForm } from "./client-scopes/add/RoleMappingForm";
import { RealmRoleTabs } from "./realm-roles/RealmRoleTabs"; import { RealmRoleTabs } from "./realm-roles/RealmRoleTabs";
import { SearchGroups } from "./groups/SearchGroups"; import { SearchGroups } from "./groups/SearchGroups";
import { CreateInitialAccessToken } from "./clients/initial-access/CreateInitialAccessToken"; import { CreateInitialAccessToken } from "./clients/initial-access/CreateInitialAccessToken";
import { RealmSettingsTabs } from "./realm-settings/RealmSettingsTabs";
import { LdapMapperDetails } from "./user-federation/ldap/mappers/LdapMapperDetails"; import { LdapMapperDetails } from "./user-federation/ldap/mappers/LdapMapperDetails";
import { AddIdentityProvider } from "./identity-providers/add/AddIdentityProvider"; import { AddIdentityProvider } from "./identity-providers/add/AddIdentityProvider";
@ -179,12 +178,6 @@ export const routes: RoutesFn = (t: TFunction) => [
breadcrumb: t("realmSettings"), breadcrumb: t("realmSettings"),
access: "view-realm", access: "view-realm",
}, },
{
path: "/:realm/realm-settings/general",
component: RealmSettingsTabs,
breadcrumb: t("realmSettings"),
access: "view-realm",
},
{ {
path: "/:realm/authentication", path: "/:realm/authentication",
component: AuthenticationSection, component: AuthenticationSection,