2022-08-03 12:12:07 +00:00
|
|
|
import { useEffect, useState } from "react";
|
2021-10-25 14:38:54 +00:00
|
|
|
import { useTranslation } from "react-i18next";
|
2021-12-01 07:58:25 +00:00
|
|
|
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,
|
2022-04-20 17:11:46 +00:00
|
|
|
} from "../components/key-value-form/AttributeForm";
|
2021-12-01 07:58:25 +00:00
|
|
|
import {
|
2022-04-20 17:11:46 +00:00
|
|
|
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;
|
|
|
|
};
|
|
|
|
|
2021-12-01 07:58:25 +00:00
|
|
|
export const UserAttributes = ({ user: defaultUser }: UserAttributesProps) => {
|
2021-10-25 14:38:54 +00:00
|
|
|
const { t } = useTranslation("users");
|
2022-07-14 13:02:28 +00:00
|
|
|
const { adminClient } = useAdminClient();
|
2021-10-25 14:38:54 +00:00
|
|
|
const { addAlert, addError } = useAlerts();
|
2021-12-01 07:58:25 +00:00
|
|
|
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>) => {
|
2022-04-20 17:11:46 +00:00
|
|
|
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 {
|
2022-04-20 17:11:46 +00:00
|
|
|
const attributes = keyValueToArray(attributeForm.attributes!);
|
2021-10-25 14:38:54 +00:00
|
|
|
await adminClient.users.update({ id: user.id! }, { ...user, attributes });
|
|
|
|
|
2021-12-01 07:58:25 +00:00
|
|
|
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}
|
2022-04-21 15:03:48 +00:00
|
|
|
fineGrainedAccess={user.access?.manage}
|
2021-10-25 14:38:54 +00:00
|
|
|
reset={() =>
|
|
|
|
form.reset({
|
|
|
|
attributes: convertAttributes(),
|
|
|
|
})
|
|
|
|
}
|
|
|
|
/>
|
|
|
|
</PageSection>
|
|
|
|
);
|
|
|
|
};
|