Ream-settings -> User Profile -> Edit Attribute (#2343)

* edit attribute - wip

* edit attribute - wip

* edit attribute - wip

* edit attribute - wip

* edit attribute - wip

* edit attribute - wip

* edit attribute - wip

* edit attribute - wip

* edit attribute - wip

* edit attribute - wip

* edit attribute - wip

* edit attribute - wip

* edit attribute - wip

* edit attribute - wip

* edit attribute - wip

* edit attribute - wip

* refactor

* refactor

* refactor

* refactor

* refactor

* refactor

* refactor

* moved form initialisation to central place

* fixed loading values

Co-authored-by: Agnieszka Gancarczyk <agancarc@redhat.com>
Co-authored-by: Erik Jan de Wit <erikjan.dewit@gmail.com>
This commit is contained in:
agagancarczyk 2022-03-31 14:28:48 +01:00 committed by GitHub
parent be2d7e268e
commit 4c70064bd4
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
8 changed files with 297 additions and 239 deletions

View file

@ -8,33 +8,32 @@ import {
} from "@patternfly/react-core";
import { FormProvider, useForm, useFormContext } from "react-hook-form";
import { useTranslation } from "react-i18next";
import { Link, useHistory } from "react-router-dom";
import { Link, useHistory, useParams } from "react-router-dom";
import { ScrollForm } from "../components/scroll-form/ScrollForm";
import { useRealm } from "../context/realm-context/RealmContext";
import type UserProfileConfig from "@keycloak/keycloak-admin-client/lib/defs/userProfileConfig";
import { AttributeGeneralSettings } from "./user-profile/attribute/AttributeGeneralSettings";
import { AttributePermission } from "./user-profile/attribute/AttributePermission";
import { AttributeValidations } from "./user-profile/attribute/AttributeValidations";
import { toUserProfile } from "./routes/UserProfile";
import "./realm-settings-section.css";
import { ViewHeader } from "../components/view-header/ViewHeader";
import { AttributeAnnotations } from "./user-profile/attribute/AttributeAnnotations";
import { useAdminClient, useFetch } from "../context/auth/AdminClient";
import { useAlerts } from "../components/alert/Alerts";
import { UserProfileProvider } from "./user-profile/UserProfileContext";
import type { UserProfileAttribute } from "@keycloak/keycloak-admin-client/lib/defs/userProfileConfig";
import type { AttributeParams } from "./routes/Attribute";
import type { KeyValueType } from "../components/attribute-form/attribute-convert";
import type ClientScopeRepresentation from "@keycloak/keycloak-admin-client/lib/defs/clientScopeRepresentation";
import { convertToFormValues } from "../util";
import { flatten } from "flat";
type UserProfileAttributeType = UserProfileAttribute &
AttributeRequired &
Permission;
import "./realm-settings-section.css";
type AttributeRequired = {
type UserProfileAttributeType = UserProfileAttribute & Attribute & Permission;
type Attribute = {
roles: string[];
scopeRequired: string[];
enabledWhen: boolean;
requiredWhen: boolean;
scopes: string[];
isRequired: boolean;
};
type Permission = {
@ -63,7 +62,8 @@ const CreateAttributeFormContent = ({
}) => {
const { t } = useTranslation("realm-settings");
const form = useFormContext();
const { realm } = useRealm();
const { realm, attributeName } = useParams<AttributeParams>();
const editMode = attributeName ? true : false;
return (
<UserProfileProvider>
@ -87,7 +87,7 @@ const CreateAttributeFormContent = ({
type="submit"
data-testid="attribute-create"
>
{t("common:create")}
{editMode ? t("common:save") : t("common:create")}
</Button>
<Link
to={toUserProfile({ realm, tab: "attributes" })}
@ -103,51 +103,51 @@ const CreateAttributeFormContent = ({
};
export default function NewAttributeSettings() {
const { realm: realmName } = useRealm();
const { realm, attributeName } = useParams<AttributeParams>();
const adminClient = useAdminClient();
const form = useForm<UserProfileConfig>();
const form = useForm<UserProfileConfig>({ shouldUnregister: false });
const { t } = useTranslation("realm-settings");
const history = useHistory();
const { addAlert, addError } = useAlerts();
const [config, setConfig] = useState<UserProfileConfig | null>(null);
const [clientScopes, setClientScopes] =
useState<ClientScopeRepresentation[]>();
const editMode = attributeName ? true : false;
const convert = (obj: Record<string, unknown>[] | undefined) =>
Object.entries(obj || []).map(([key, value]) => ({
key,
value,
}));
useFetch(
() =>
Promise.all([
adminClient.users.getProfile({ realm: realmName }),
adminClient.clientScopes.find(),
]),
([config, clientScopes]) => {
() => adminClient.users.getProfile({ realm }),
(config) => {
setConfig(config);
setClientScopes(clientScopes);
const {
annotations,
validations,
permissions,
selector,
required,
...values
} = config.attributes!.find(
(attribute) => attribute.name === attributeName
)!;
convertToFormValues(values, form.setValue);
Object.entries(
flatten({ permissions, selector, required }, { safe: true })
).map(([key, value]) => form.setValue(key, value));
form.setValue("annotations", convert(annotations));
form.setValue("validations", convert(validations));
form.setValue("isRequired", required !== undefined);
},
[]
);
const save = async (profileConfig: UserProfileAttributeType) => {
const scopeNames = clientScopes?.map((clientScope) => clientScope.name);
const selector = {
scopes: profileConfig.enabledWhen
? scopeNames
: profileConfig.selector?.scopes,
};
const required = {
roles: profileConfig.roles,
scopes: profileConfig.requiredWhen
? scopeNames
: profileConfig.scopeRequired,
};
const validations = profileConfig.validations?.reduce(
(prevValidations: any, currentValidations: any) => {
prevValidations[currentValidations.name] =
currentValidations.config.length === 0
? {}
: currentValidations.config;
prevValidations[currentValidations.key] =
currentValidations.value.length === 0 ? {} : currentValidations.value;
return prevValidations;
},
{}
@ -158,29 +158,55 @@ export default function NewAttributeSettings() {
{}
);
const newAttribute = [
{
name: profileConfig.name,
displayName: profileConfig.displayName,
required,
validations,
selector,
permissions: profileConfig.permissions,
annotations,
},
];
const patchAttributes = () =>
config?.attributes!.map((attribute) => {
if (attribute.name !== attributeName) {
return attribute;
}
const newAttributesList = config?.attributes!.concat(
newAttribute as UserProfileAttribute
);
return Object.assign(
{
...attribute,
name: attributeName,
displayName: profileConfig.displayName!,
validations,
selector: profileConfig.selector,
permissions: profileConfig.permissions!,
annotations,
},
profileConfig.isRequired
? { required: profileConfig.required }
: undefined
);
});
const addAttribute = () =>
config?.attributes!.concat([
Object.assign(
{
name: profileConfig.name,
displayName: profileConfig.displayName!,
required: profileConfig.isRequired ? profileConfig.required : {},
validations,
selector: profileConfig.selector,
permissions: profileConfig.permissions!,
annotations,
},
profileConfig.isRequired
? { required: profileConfig.required }
: undefined
),
] as UserProfileAttribute);
const updatedAttributes = editMode ? patchAttributes() : addAttribute();
try {
await adminClient.users.updateProfile({
attributes: newAttributesList,
realm: realmName,
attributes: updatedAttributes as UserProfileAttribute[],
realm,
});
history.push(toUserProfile({ realm: realmName, tab: "attributes" }));
history.push(toUserProfile({ realm, tab: "attributes" }));
addAlert(
t("realm-settings:createAttributeSuccess"),
@ -194,8 +220,8 @@ export default function NewAttributeSettings() {
return (
<FormProvider {...form}>
<ViewHeader
titleKey={t("createAttribute")}
subKey={t("createAttributeSubTitle")}
titleKey={editMode ? attributeName : t("createAttribute")}
subKey={editMode ? "" : t("createAttributeSubTitle")}
/>
<PageSection variant="light">
<CreateAttributeFormContent save={() => form.handleSubmit(save)()} />

View file

@ -404,6 +404,7 @@ export default {
updatedUserProfileSuccess: "User Profile configuration has been saved",
updatedUserProfileError: "User Profile configuration hasn't been saved",
createAttribute: "Create attribute",
editAttribute: "Edit attribute",
createAttributeSubTitle: "Create a new attribute",
createAttributeSuccess:
"Success! User Profile configuration has been saved.",
@ -415,6 +416,8 @@ export default {
"Are you sure you want to permanently delete the attribute {{attributeName}}?",
deleteAttributeSuccess: "Attribute deleted",
deleteAttributeError: "Attribute not deleted",
always: "Always",
scopesAsRequested: "Scopes are requested",
generalSettings: "General settings",
permission: "Permission",
validations: "Validations",

View file

@ -11,7 +11,7 @@ export type AttributeParams = {
export const AttributeRoute: RouteDef = {
path: "/:realm/realm-settings/userProfile/attributes/:attributeName/edit-attribute",
component: lazy(() => import("../NewAttributeSettings")),
breadcrumb: (t) => t("realm-settings:createAttribute"),
breadcrumb: (t) => t("realm-settings:editAttribute"),
access: "manage-realm",
};

View file

@ -59,8 +59,6 @@ export const AttributesTab = () => {
);
};
const goToCreate = () => history.push(toAddAttribute({ realm: realmName }));
const updatedAttributes = config?.attributes!.filter(
(attribute) => attribute.name !== attributeToDelete
);
@ -173,7 +171,14 @@ export const AttributesTab = () => {
actions={[
{
title: t("common:edit"),
onClick: goToCreate,
onClick: (_key, _idx, component) => {
history.push(
toAttribute({
realm: realmName,
attributeName: component.name,
})
);
},
},
{
title: t("common:delete"),

View file

@ -1,15 +1,14 @@
import React from "react";
import { FormGroup, Grid, GridItem } from "@patternfly/react-core";
import { useTranslation } from "react-i18next";
import { FormGroup, Grid, GridItem } from "@patternfly/react-core";
import { FormAccess } from "../../../components/form-access/FormAccess";
import { FormProvider, useFormContext } from "react-hook-form";
import { AttributeInput } from "../../../components/attribute-input/AttributeInput";
import "../../realm-settings-section.css";
export const AttributeAnnotations = () => {
const { t } = useTranslation("realm-settings");
const form = useFormContext();
return (
<FormAccess role="manage-realm" isHorizontal>
@ -21,9 +20,7 @@ export const AttributeAnnotations = () => {
>
<Grid className="kc-annotations">
<GridItem>
<FormProvider {...form}>
<AttributeInput name="annotations" />
</FormProvider>
<AttributeInput name="annotations" />
</GridItem>
</Grid>
</FormGroup>

View file

@ -17,9 +17,12 @@ import { Controller, useFormContext, useWatch } from "react-hook-form";
import { FormAccess } from "../../../components/form-access/FormAccess";
import { useAdminClient, useFetch } from "../../../context/auth/AdminClient";
import type ClientScopeRepresentation from "@keycloak/keycloak-admin-client/lib/defs/clientScopeRepresentation";
import type { AttributeParams } from "../../routes/Attribute";
import { useParams } from "react-router-dom";
import { isEqual } from "lodash-es";
import "../../realm-settings-section.css";
const ENABLED_REQUIRED_WHEN = ["Always", "Scopes are requested"] as const;
const REQUIRED_FOR = [
{ label: "Both users and admins", value: ["admin", "user"] },
{ label: "Only users", value: ["user"] },
@ -36,12 +39,24 @@ export const AttributeGeneralSettings = () => {
const [selectRequiredForOpen, setSelectRequiredForOpen] = useState(false);
const [isAttributeGroupDropdownOpen, setIsAttributeGroupDropdownOpen] =
useState(false);
const [enabledWhenSelection, setEnabledWhenSelection] = useState("Always");
const [requiredWhenSelection, setRequiredWhenSelection] = useState("Always");
const { attributeName } = useParams<AttributeParams>();
const editMode = attributeName ? true : false;
const requiredToggle = useWatch({
const selectedScopes = useWatch({
control: form.control,
name: "required",
name: "selector.scopes",
defaultValue: [],
});
const requiredScopes = useWatch({
control: form.control,
name: "required.scopes",
defaultValue: [],
});
const required = useWatch({
control: form.control,
name: "isRequired",
defaultValue: false,
});
@ -77,10 +92,11 @@ export const AttributeGeneralSettings = () => {
ref={form.register({
required: {
value: true,
message: `${t("validateName")}`,
message: t("validateName"),
},
})}
data-testid="attribute-name"
isDisabled={editMode}
validated={form.errors.name ? "error" : "default"}
/>
</FormGroup>
@ -141,44 +157,49 @@ export const AttributeGeneralSettings = () => {
</FormGroup>
<Divider />
<FormGroup label={t("enabledWhen")} fieldId="enabledWhen" hasNoPaddingTop>
<Controller
<Radio
id="always"
data-testid="always"
isChecked={selectedScopes.length === clientScopes?.length}
name="enabledWhen"
data-testid="enabledWhen"
control={form.control}
defaultValue={ENABLED_REQUIRED_WHEN[0]}
render={({ onChange, value }) => (
<>
{ENABLED_REQUIRED_WHEN.map((option) => (
<Radio
id={option}
key={option}
data-testid={option}
isChecked={value === option}
name="enabledWhen"
onChange={() => {
onChange(option);
setEnabledWhenSelection(option);
}}
label={option}
className="pf-u-mb-md"
/>
))}
</>
)}
label={t("always")}
onChange={(value) => {
if (value) {
form.setValue(
"selector.scopes",
clientScopes?.map((s) => s.name)
);
} else {
form.setValue("selector.scopes", []);
}
}}
className="pf-u-mb-md"
/>
<Radio
id="scopesAsRequested"
data-testid="scopesAsRequested"
isChecked={selectedScopes.length !== clientScopes?.length}
name="enabledWhen"
label={t("scopesAsRequested")}
onChange={(value) => {
if (value) {
form.setValue("selector.scopes", []);
} else {
form.setValue(
"selector.scopes",
clientScopes?.map((s) => s.name)
);
}
}}
className="pf-u-mb-md"
/>
</FormGroup>
<FormGroup fieldId="kc-scope-enabled-when">
<Controller
name="scopes"
name="selector.scopes"
control={form.control}
defaultValue={[]}
render={({
onChange,
value,
}: {
onChange: (newValue: string[]) => void;
value: string[];
}) => (
render={({ onChange, value }) => (
<Select
name="scopes"
data-testid="enabled-when-scope-field"
@ -196,7 +217,7 @@ export const AttributeGeneralSettings = () => {
let changedValue = [""];
if (value) {
changedValue = value.includes(option)
? value.filter((item) => item !== option)
? value.filter((item: string) => item !== option)
: [...value, option];
} else {
changedValue = [option];
@ -209,7 +230,7 @@ export const AttributeGeneralSettings = () => {
onChange([]);
}}
isOpen={selectEnabledWhenOpen}
isDisabled={enabledWhenSelection === "Always"}
isDisabled={selectedScopes.length === clientScopes?.length}
aria-labelledby={"scope"}
>
{clientScopes?.map((option) => (
@ -232,24 +253,22 @@ export const AttributeGeneralSettings = () => {
hasNoPaddingTop
>
<Controller
name="required"
name="isRequired"
data-testid="required"
defaultValue={false}
control={form.control}
render={({ onChange, value }) => (
<Switch
id={"kc-required"}
onChange={(value) => {
onChange(value);
form.setValue("required", value);
}}
isChecked={value === true}
onChange={onChange}
isChecked={value}
label={t("common:on")}
labelOff={t("common:off")}
/>
)}
></Controller>
/>
</FormGroup>
{requiredToggle && (
{required && (
<>
<FormGroup
label={t("requiredFor")}
@ -257,7 +276,7 @@ export const AttributeGeneralSettings = () => {
hasNoPaddingTop
>
<Controller
name="roles"
name="required.roles"
data-testid="requiredFor"
defaultValue={REQUIRED_FOR[0].value}
control={form.control}
@ -267,10 +286,12 @@ export const AttributeGeneralSettings = () => {
<Radio
id={option.label}
key={option.label}
data-testid={option}
isChecked={value === option.value}
data-testid={option.label}
isChecked={isEqual(value, option.value)}
name="roles"
onChange={() => onChange(option.value)}
onChange={() => {
onChange(option.value);
}}
label={option.label}
className="kc-requiredFor-option"
/>
@ -284,44 +305,49 @@ export const AttributeGeneralSettings = () => {
fieldId="requiredWhen"
hasNoPaddingTop
>
<Controller
<Radio
id="requiredAlways"
data-testid="requiredAlways"
isChecked={requiredScopes.length === clientScopes?.length}
name="requiredWhen"
data-testid="requiredWhen"
defaultValue={ENABLED_REQUIRED_WHEN[0]}
control={form.control}
render={({ onChange, value }) => (
<>
{ENABLED_REQUIRED_WHEN.map((option) => (
<Radio
id={option}
key={option}
data-testid={option}
isChecked={value === option}
name="requiredWhen"
onChange={() => {
onChange(option);
setRequiredWhenSelection(option);
}}
label={option}
className="pf-u-mb-md"
/>
))}
</>
)}
label={t("always")}
onChange={(value) => {
if (value) {
form.setValue(
"required.scopes",
clientScopes?.map((s) => s.name)
);
} else {
form.setValue("required.scopes", []);
}
}}
className="pf-u-mb-md"
/>
<Radio
id="requiredScopesAsRequested"
data-testid="requiredScopesAsRequested"
isChecked={requiredScopes.length !== clientScopes?.length}
name="requiredWhen"
label={t("scopesAsRequested")}
onChange={(value) => {
if (value) {
form.setValue("required.scopes", []);
} else {
form.setValue(
"required.scopes",
clientScopes?.map((s) => s.name)
);
}
}}
className="pf-u-mb-md"
/>
</FormGroup>
<FormGroup fieldId="kc-scope-required-when">
<Controller
name="scopeRequired"
name="required.scopes"
control={form.control}
defaultValue={[]}
render={({
onChange,
value,
}: {
onChange: (newValue: string[]) => void;
value: string[];
}) => (
render={({ onChange, value }) => (
<Select
name="scopeRequired"
data-testid="required-when-scope-field"
@ -339,7 +365,7 @@ export const AttributeGeneralSettings = () => {
let changedValue = [""];
if (value) {
changedValue = value.includes(option)
? value.filter((item) => item !== option)
? value.filter((item: string) => item !== option)
: [...value, option];
} else {
changedValue = [option];
@ -351,7 +377,7 @@ export const AttributeGeneralSettings = () => {
onChange([]);
}}
isOpen={selectRequiredForOpen}
isDisabled={requiredWhenSelection === "Always"}
isDisabled={requiredScopes.length === clientScopes?.length}
aria-labelledby={"scope"}
>
{clientScopes?.map((option) => (

View file

@ -9,57 +9,53 @@ import "../../realm-settings-section.css";
const Permissions = ({ name }: { name: string }) => {
const { t } = useTranslation("realm-settings");
const { control } = useFormContext();
return (
<Grid>
<GridItem lg={4} sm={6}>
<Controller
name={`permissions.${name}`}
control={control}
defaultValue={[]}
render={({ onChange, value }) => (
<Checkbox
id={`user-${name}`}
label={t("user")}
value="user"
data-testid={`user-${name}`}
isChecked={value.includes("user")}
onChange={() => {
const option = "user";
const changedValue = value.includes(option)
? value.filter((item: string) => item !== option)
: [option];
<Controller
name={`permissions.${name}`}
control={control}
defaultValue={[]}
render={({ onChange, value }) => (
<>
<GridItem lg={4} sm={6}>
<Checkbox
id={`user-${name}`}
label={t("user")}
value="user"
data-testid={`user-${name}`}
isChecked={value.includes("user")}
onChange={() => {
const option = "user";
const changedValue = value.includes(option)
? value.filter((item: string) => item !== option)
: [option];
onChange(changedValue);
}}
isDisabled={value.includes("admin")}
/>
)}
/>
</GridItem>
<GridItem lg={8} sm={6}>
<Controller
name={`permissions.${name}`}
control={control}
defaultValue={[]}
render={({ onChange, value }) => (
<Checkbox
id={`admin-${name}`}
label={t("admin")}
value="admin"
data-testid={`admin-${name}`}
isChecked={value.includes("admin")}
onChange={() => {
const option = "admin";
const changedValue = value.includes(option)
? value.filter((item: string) => item !== option)
: ["user", option];
onChange(changedValue);
}}
isDisabled={value.includes("admin")}
/>
</GridItem>
<GridItem lg={8} sm={6}>
<Checkbox
id={`admin-${name}`}
label={t("admin")}
value="admin"
data-testid={`admin-${name}`}
isChecked={value.includes("admin")}
onChange={() => {
const option = "admin";
const changedValue = value.includes(option)
? value.filter((item: string) => item !== option)
: ["user", option];
onChange(changedValue);
}}
/>
)}
/>
</GridItem>
onChange(changedValue);
}}
/>
</GridItem>
</>
)}
/>
</Grid>
);
};

View file

@ -1,4 +1,3 @@
/* eslint-disable @typescript-eslint/no-unnecessary-condition */
import React, { useEffect, useState } from "react";
import {
Button,
@ -22,26 +21,29 @@ import {
Tr,
} from "@patternfly/react-table";
import { useConfirmDialog } from "../../../components/confirm-dialog/ConfirmDialog";
import type { Validator } from "./Validators";
import useToggle from "../../../utils/useToggle";
import { useFormContext, useWatch } from "react-hook-form";
import type { KeyValueType } from "../../../components/attribute-form/attribute-convert";
import "../../realm-settings-section.css";
export const AttributeValidations = () => {
const { t } = useTranslation("realm-settings");
const [addValidatorModalOpen, toggleModal] = useToggle();
const [validatorToDelete, setValidatorToDelete] = useState<{
name: string;
}>();
const [validatorToDelete, setValidatorToDelete] =
useState<{ name: string }>();
const { setValue, control, register } = useFormContext();
const validators = useWatch<Validator[]>({
const validators = useWatch<KeyValueType[]>({
name: "validations",
control,
defaultValue: [],
});
useEffect(() => register("validations"), []);
useEffect(() => {
register("validations");
}, []);
const [toggleDeleteDialog, DeleteConfirm] = useConfirmDialog({
titleKey: t("deleteValidatorConfirmTitle"),
@ -52,8 +54,9 @@ export const AttributeValidations = () => {
continueButtonVariant: ButtonVariant.danger,
onConfirm: async () => {
const updatedValidators = validators.filter(
(validator) => validator.name !== validatorToDelete?.name
(validator) => validator.key !== validatorToDelete?.name
);
setValue("validations", [...updatedValidators]);
},
});
@ -63,7 +66,10 @@ export const AttributeValidations = () => {
{addValidatorModalOpen && (
<AddValidatorDialog
onConfirm={(newValidator) => {
setValue("validations", [...validators, newValidator]);
setValue("validations", [
...validators,
{ key: newValidator.name, value: newValidator.config },
]);
}}
toggleDialog={toggleModal}
/>
@ -94,33 +100,32 @@ export const AttributeValidations = () => {
</Tr>
</Thead>
<Tbody>
{validators.length ? (
validators.map((validator: Validator) => (
<Tr key={validator.name}>
<Td dataLabel={t("validatorColNames.colName")}>
{validator.name}
</Td>
<Td dataLabel={t("validatorColNames.colConfig")}>
{JSON.stringify(validator.config)}
</Td>
<Td>
<Button
key="validator"
variant="link"
data-testid="deleteValidator"
onClick={() => {
toggleDeleteDialog();
setValidatorToDelete({
name: validator.name,
});
}}
>
{t("common:delete")}
</Button>
</Td>
</Tr>
))
) : (
{validators.map((validator) => (
<Tr key={validator.key}>
<Td dataLabel={t("validatorColNames.colName")}>
{validator.key}
</Td>
<Td dataLabel={t("validatorColNames.colConfig")}>
{JSON.stringify(validator.value)}
</Td>
<Td>
<Button
key="validator"
variant="link"
data-testid="deleteValidator"
onClick={() => {
toggleDeleteDialog();
setValidatorToDelete({
name: validator.key,
});
}}
>
{t("common:delete")}
</Button>
</Td>
</Tr>
))}
{validators.length === 0 && (
<Text className="kc-emptyValidators" component={TextVariants.h6}>
{t("realm-settings:emptyValidators")}
</Text>