made realm name editable (#1001)

Co-authored-by: Jon Koops <jonkoops@gmail.com>
This commit is contained in:
Erik Jan de Wit 2021-08-23 21:00:42 +02:00 committed by GitHub
parent d42560aaf0
commit 89870cafc2
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 100 additions and 97 deletions

View file

@ -45,14 +45,10 @@ export const RealmContextProvider: FunctionComponent = ({ children }) => {
useEffect(() => adminClient.setConfig({ realmName: realm }), [realm]);
const set = (realm: string) => {
if (
realms.length === 0 ||
realms.findIndex((r) => r.realm == realm) !== -1
) {
recentUsed.setRecentUsed(realm);
setRealm(realm);
}
recentUsed.setRecentUsed(realm);
setRealm(realm);
};
return (
<RealmContext.Provider
value={{
@ -60,6 +56,9 @@ export const RealmContextProvider: FunctionComponent = ({ children }) => {
setRealm: set,
realms,
refresh: async () => {
//this is needed otherwise the realm find function will not return
//new or renamed realms because of the cached realms in the token (perhaps?)
await adminClient.keycloak?.updateToken(Number.MAX_VALUE);
const list = await adminClient.realms.find();
updateRealmsList(list);
},

View file

@ -58,7 +58,14 @@ export const RealmSettingsGeneralTab = ({
onSubmit={handleSubmit(save)}
>
<FormGroup label={t("realmId")} fieldId="kc-realm-id" isRequired>
<ClipboardCopy isReadOnly>{realmName}</ClipboardCopy>
<Controller
name="realm"
control={control}
defaultValue=""
render={({ onChange, value }) => (
<ClipboardCopy onChange={onChange}>{value}</ClipboardCopy>
)}
/>
</FormGroup>
<FormGroup label={t("displayName")} fieldId="kc-display-name">
<TextInput

View file

@ -6,6 +6,7 @@ import {
DropdownItem,
DropdownSeparator,
PageSection,
Spinner,
Tab,
Tabs,
TabTitleText,
@ -26,7 +27,7 @@ import { useRealm } from "../context/realm-context/RealmContext";
import { useServerInfo } from "../context/server-info/ServerInfoProvider";
import { LocalizationTab } from "./LocalizationTab";
import { useWhoAmI } from "../context/whoami/WhoAmI";
import { KEY_PROVIDER_TYPE, toUpperCase } from "../util";
import { convertToFormValues, KEY_PROVIDER_TYPE, toUpperCase } from "../util";
import { RealmSettingsEmailTab } from "./EmailTab";
import { EventsTab } from "./event-config/EventsTab";
import { RealmSettingsGeneralTab } from "./GeneralTab";
@ -165,7 +166,11 @@ const sortByPriority = (components: ComponentRepresentation[]) => {
export const RealmSettingsSection = () => {
const { t } = useTranslation("realm-settings");
const adminClient = useAdminClient();
const { realm: realmName } = useRealm();
const {
realm: realmName,
refresh: refreshRealm,
setRealm: setCurrentRealm,
} = useRealm();
const { addAlert, addError } = useAlerts();
const form = useForm({ mode: "onChange" });
const { control, getValues, setValue, reset: resetForm } = form;
@ -176,6 +181,7 @@ export const RealmSettingsSection = () => {
useState<ComponentRepresentation[]>();
const [currentUser, setCurrentUser] = useState<UserRepresentation>();
const { whoAmI } = useWhoAmI();
const history = useHistory();
const kpComponentTypes =
useServerInfo().componentTypes?.[KEY_PROVIDER_TYPE] ?? [];
@ -187,7 +193,7 @@ export const RealmSettingsSection = () => {
type: KEY_PROVIDER_TYPE,
realm: realmName,
});
const user = await adminClient.users.findOne({ id: whoAmI.getUserId()! });
const user = await adminClient.users.findOne({ id: whoAmI.getUserId() });
return { user, realm, realmComponents };
},
@ -205,21 +211,43 @@ export const RealmSettingsSection = () => {
useEffect(() => {
if (realm) {
Object.entries(realm).map((entry) => setValue(entry[0], entry[1]));
resetForm({ ...realm });
Object.entries(realm).map(([key, value]) => {
if (key === "attributes") {
convertToFormValues(value, "attributes", form.setValue);
} else {
setValue(key, value);
}
});
resetForm(getValues());
}
}, [realm, resetForm]);
}, [realm]);
const save = async (realm: RealmRepresentation) => {
try {
await adminClient.realms.update({ realm: realmName }, realm);
await adminClient.realms.update(
{ realm: realmName },
{ ...realm, id: realmName }
);
setRealm(realm);
const isRealmRenamed = realmName !== realm.realm;
if (isRealmRenamed) {
await refreshRealm();
setCurrentRealm(realm.realm!);
history.push(toRealmSettings({ realm: realm.realm! }));
}
addAlert(t("saveSuccess"), AlertVariant.success);
} catch (error) {
addError("realm-settings:saveError", error);
}
};
if (!realm || !realmComponents || !currentUser) {
return (
<div className="pf-u-text-align-center">
<Spinner />
</div>
);
}
return (
<>
<Controller
@ -255,7 +283,7 @@ export const RealmSettingsSection = () => {
data-testid="rs-login-tab"
aria-label="login-tab"
>
<RealmSettingsLoginTab save={save} realm={realm!} />
<RealmSettingsLoginTab save={save} realm={realm} />
</Tab>
<Tab
eventKey="email"
@ -263,9 +291,7 @@ export const RealmSettingsSection = () => {
data-testid="rs-email-tab"
aria-label="email-tab"
>
{realm && (
<RealmSettingsEmailTab user={currentUser!} realm={realm} />
)}
<RealmSettingsEmailTab user={currentUser} realm={realm} />
</Tab>
<Tab
eventKey="themes"
@ -276,7 +302,7 @@ export const RealmSettingsSection = () => {
<RealmSettingsThemesTab
save={save}
reset={() => resetForm(realm)}
realm={realm!}
realm={realm}
/>
</Tab>
<Tab
@ -285,35 +311,33 @@ export const RealmSettingsSection = () => {
data-testid="rs-keys-tab"
aria-label="keys-tab"
>
{realmComponents && (
<Tabs
activeKey={activeTab}
onSelect={(_, key) => setActiveTab(key as number)}
<Tabs
activeKey={activeTab}
onSelect={(_, key) => setActiveTab(Number(key))}
>
<Tab
id="keysList"
eventKey={0}
data-testid="rs-keys-list-tab"
aria-label="keys-list-subtab"
title={<TabTitleText>{t("keysList")}</TabTitleText>}
>
<Tab
id="keysList"
eventKey={0}
data-testid="rs-keys-list-tab"
aria-label="keys-list-subtab"
title={<TabTitleText>{t("keysList")}</TabTitleText>}
>
<KeysListTab realmComponents={realmComponents} />
</Tab>
<Tab
id="providers"
data-testid="rs-providers-tab"
aria-label="rs-providers-tab"
eventKey={1}
title={<TabTitleText>{t("providers")}</TabTitleText>}
>
<KeysProvidersTab
realmComponents={realmComponents}
keyProviderComponentTypes={kpComponentTypes}
refresh={refresh}
/>
</Tab>
</Tabs>
)}
<KeysListTab realmComponents={realmComponents} />
</Tab>
<Tab
id="providers"
data-testid="rs-providers-tab"
aria-label="rs-providers-tab"
eventKey={1}
title={<TabTitleText>{t("providers")}</TabTitleText>}
>
<KeysProvidersTab
realmComponents={realmComponents}
keyProviderComponentTypes={kpComponentTypes}
refresh={refresh}
/>
</Tab>
</Tabs>
</Tab>
<Tab
eventKey="events"
@ -329,24 +353,20 @@ export const RealmSettingsSection = () => {
data-testid="rs-localization-tab"
title={<TabTitleText>{t("localization")}</TabTitleText>}
>
{realm && (
<LocalizationTab
key={key}
refresh={refresh}
save={save}
reset={() => resetForm(realm)}
realm={realm}
/>
)}
<LocalizationTab
key={key}
refresh={refresh}
save={save}
reset={() => resetForm(realm)}
realm={realm}
/>
</Tab>
<Tab
id="securityDefences"
eventKey="securityDefences"
title={<TabTitleText>{t("securityDefences")}</TabTitleText>}
>
{realm && (
<SecurityDefences save={save} reset={() => resetForm(realm)} />
)}
<SecurityDefences save={save} reset={() => resetForm(realm)} />
</Tab>
<Tab
id="sessions"
@ -357,7 +377,7 @@ export const RealmSettingsSection = () => {
<TabTitleText>{t("realm-settings:sessions")}</TabTitleText>
}
>
{realm && <RealmSettingsSessionsTab key={key} realm={realm} />}
<RealmSettingsSessionsTab key={key} realm={realm} />
</Tab>
<Tab
id="tokens"
@ -366,7 +386,10 @@ export const RealmSettingsSection = () => {
aria-label="tokens-tab"
title={<TabTitleText>{t("realm-settings:tokens")}</TabTitleText>}
>
<RealmSettingsTokensTab reset={() => resetForm(realm)} />
<RealmSettingsTokensTab
realm={realm}
reset={() => resetForm(realm)}
/>
</Tab>
</KeycloakTabs>
</FormProvider>

View file

@ -1,6 +1,6 @@
import React, { useState } from "react";
import { useTranslation } from "react-i18next";
import { Controller, useForm, useFormContext, useWatch } from "react-hook-form";
import { Controller, useFormContext, useWatch } from "react-hook-form";
import {
ActionGroup,
AlertVariant,
@ -20,7 +20,7 @@ import type RealmRepresentation from "keycloak-admin/lib/defs/realmRepresentatio
import { FormAccess } from "../components/form-access/FormAccess";
import { HelpItem } from "../components/help-enabler/HelpItem";
import { FormPanel } from "../components/scroll-form/FormPanel";
import { useAdminClient, useFetch } from "../context/auth/AdminClient";
import { useAdminClient } from "../context/auth/AdminClient";
import { useAlerts } from "../components/alert/Alerts";
import { useRealm } from "../context/realm-context/RealmContext";
@ -29,7 +29,6 @@ import type UserRepresentation from "keycloak-admin/lib/defs/userRepresentation"
import { TimeSelector } from "../components/time-selector/TimeSelector";
import { useServerInfo } from "../context/server-info/ServerInfoProvider";
import {
convertToFormValues,
forHumans,
flatten,
convertFormValuesToObject,
@ -37,7 +36,7 @@ import {
} from "../util";
type RealmSettingsSessionsTabProps = {
realm?: RealmRepresentation;
realm: RealmRepresentation;
user?: UserRepresentation;
reset?: () => void;
};
@ -70,8 +69,8 @@ export const RealmSettingsTokensTab = ({
javaKeystoreAlgOptions!
);
const form = useForm<RealmRepresentation>();
const { control } = useFormContext();
const form = useFormContext<RealmRepresentation>();
const { control } = form;
const offlineSessionMaxEnabled = useWatch({
control,
@ -79,27 +78,6 @@ export const RealmSettingsTokensTab = ({
defaultValue: realm?.offlineSessionMaxLifespanEnabled,
});
const setupForm = (realm: RealmRepresentation) => {
const { ...formValues } = realm;
form.reset(formValues);
Object.entries(realm).map((entry) => {
if (entry[0] === "attributes") {
convertToFormValues(entry[1], "attributes", form.setValue);
} else {
form.setValue(entry[0], entry[1]);
}
});
};
useFetch(
() => adminClient.realms.findOne({ realm: realmName }),
(realm) => {
setRealm(realm);
setupForm(realm);
},
[realmName]
);
const save = async () => {
const firstInstanceOnly = true;
const flattenedAttributes = convertFormValuesToObject(
@ -107,18 +85,15 @@ export const RealmSettingsTokensTab = ({
firstInstanceOnly
);
const attributes = { ...flattenedAttributes, ...realm?.attributes };
try {
const newRealm: RealmRepresentation = {
...realm,
...form.getValues(),
attributes,
attributes: flattenedAttributes,
};
await adminClient.realms.update({ realm: realmName }, newRealm);
setupForm(newRealm);
setRealm(newRealm);
addAlert(t("saveSuccess"), AlertVariant.success);
} catch (error) {

View file

@ -23,7 +23,7 @@ export default {
saveProviderListSuccess:
"The priority of the provider has been updated successfully.",
saveProviderError: "Error saving provider: ",
saveError: "Realm could not be updated: {error}",
saveError: "Realm could not be updated: {{error}}",
general: "General",
login: "Login",
themes: "Themes",

View file

@ -24,7 +24,7 @@ export const NewRealmForm = () => {
const { t } = useTranslation("realm");
const history = useHistory();
const { refresh } = useWhoAmI();
const { refresh: realmRefresh } = useRealm();
const { refresh: realmRefresh, setRealm } = useRealm();
const adminClient = useAdminClient();
const { addAlert, addError } = useAlerts();
@ -43,10 +43,9 @@ export const NewRealmForm = () => {
await adminClient.realms.create(realm);
addAlert(t("saveRealmSuccess"), AlertVariant.success);
//force token update
refresh();
await adminClient.keycloak?.updateToken(Number.MAX_VALUE);
await realmRefresh();
setRealm(realm.realm!);
history.push(`/${realm.realm}`);
} catch (error) {
addError("realm:saveRealmError", error);