keycloak-scim/apps/admin-ui/src/user/UserAttributes.tsx

69 lines
1.9 KiB
TypeScript
Raw Normal View History

import { useEffect, useState } from "react";
2021-10-25 14:38:54 +00:00
import { useTranslation } from "react-i18next";
import { useForm } from "react-hook-form";
2021-10-25 14:38:54 +00:00
import {
AlertVariant,
PageSection,
PageSectionVariants,
} from "@patternfly/react-core";
import type UserRepresentation from "@keycloak/keycloak-admin-client/lib/defs/userRepresentation";
import { useAlerts } from "../components/alert/Alerts";
import {
AttributeForm,
AttributesForm,
} from "../components/key-value-form/AttributeForm";
import {
arrayToKeyValue,
keyValueToArray,
} from "../components/key-value-form/key-value-convert";
2021-10-25 14:38:54 +00:00
import { useAdminClient } from "../context/auth/AdminClient";
type UserAttributesProps = {
user: UserRepresentation;
};
export const UserAttributes = ({ user: defaultUser }: UserAttributesProps) => {
2021-10-25 14:38:54 +00:00
const { t } = useTranslation("users");
const { adminClient } = useAdminClient();
2021-10-25 14:38:54 +00:00
const { addAlert, addError } = useAlerts();
const [user, setUser] = useState<UserRepresentation>(defaultUser);
2021-10-25 14:38:54 +00:00
const form = useForm<AttributeForm>({ mode: "onChange" });
const convertAttributes = (attr?: Record<string, any>) => {
return arrayToKeyValue(attr || user.attributes!);
2021-10-25 14:38:54 +00:00
};
useEffect(() => {
form.setValue("attributes", convertAttributes());
}, [user]);
const save = async (attributeForm: AttributeForm) => {
try {
const attributes = keyValueToArray(attributeForm.attributes!);
2021-10-25 14:38:54 +00:00
await adminClient.users.update({ id: user.id! }, { ...user, attributes });
setUser({ ...user, attributes });
2021-10-25 14:38:54 +00:00
addAlert(t("userSaved"), AlertVariant.success);
} catch (error) {
addError("groups:groupUpdateError", error);
}
};
return (
<PageSection variant={PageSectionVariants.light}>
<AttributesForm
form={form}
save={save}
fineGrainedAccess={user.access?.manage}
2021-10-25 14:38:54 +00:00
reset={() =>
form.reset({
attributes: convertAttributes(),
})
}
/>
</PageSection>
);
};