keycloak-scim/src/realm-roles/RealmRoleTabs.tsx

300 lines
9 KiB
TypeScript
Raw Normal View History

import React, { useEffect, useState } from "react";
import { useHistory, useParams, useRouteMatch } from "react-router-dom";
import {
AlertVariant,
ButtonVariant,
DropdownItem,
PageSection,
Tab,
TabTitleText,
} from "@patternfly/react-core";
import { useTranslation } from "react-i18next";
import { useFieldArray, useForm } from "react-hook-form";
import { useAlerts } from "../components/alert/Alerts";
import { useAdminClient } from "../context/auth/AdminClient";
import RoleRepresentation from "keycloak-admin/lib/defs/roleRepresentation";
import Composites from "keycloak-admin/lib/defs/roleRepresentation";
import { KeyValueType, RoleAttributes } from "./RoleAttributes";
import { ViewHeader } from "../components/view-header/ViewHeader";
import { useConfirmDialog } from "../components/confirm-dialog/ConfirmDialog";
import { RealmRoleForm } from "./RealmRoleForm";
import { useRealm } from "../context/realm-context/RealmContext";
2021-01-20 21:10:25 +00:00
import { AssociatedRolesModal } from "./AssociatedRolesModal";
import { KeycloakTabs } from "../components/keycloak-tabs/KeycloakTabs";
import { AssociatedRolesTab } from "./AssociatedRolesTab";
const arrayToAttributes = (attributeArray: KeyValueType[]) => {
const initValue: { [index: string]: string[] } = {};
return attributeArray.reduce((acc, attribute) => {
acc[attribute.key] = [attribute.value];
return acc;
}, initValue);
};
const attributesToArray = (attributes?: {
[key: string]: string[];
}): KeyValueType[] => {
if (!attributes || Object.keys(attributes).length == 0) {
return [];
}
return Object.keys(attributes).map((key) => ({
key: key,
value: attributes[key][0],
}));
};
export type RoleFormType = Omit<RoleRepresentation, "attributes"> & {
attributes: KeyValueType[];
};
export const RealmRoleTabs = () => {
const { t } = useTranslation("roles");
const form = useForm<RoleFormType>({ mode: "onChange" });
const history = useHistory();
// const [name, setName] = useState("");
const adminClient = useAdminClient();
const [role, setRole] = useState<RoleFormType>();
const { id, clientId } = useParams<{ id: string; clientId: string }>();
const { url } = useRouteMatch();
const { realm } = useRealm();
const [key, setKey] = useState("");
const refresh = () => {
setKey(`${new Date().getTime()}`);
};
const [additionalRoles, setAdditionalRoles] = useState<RoleRepresentation[]>(
[]
);
const { addAlert } = useAlerts();
2021-01-20 21:10:25 +00:00
const [open, setOpen] = useState(false);
const convert = (role: RoleRepresentation) => {
const { attributes, ...rest } = role;
return {
attributes: attributesToArray(attributes),
...rest,
};
};
2021-01-20 21:10:25 +00:00
useEffect(() => {
const update = async () => {
if (id) {
const fetchedRole = await adminClient.roles.findOneById({ id });
const allAdditionalRoles = await adminClient.roles.getCompositeRoles({
id,
});
setAdditionalRoles(allAdditionalRoles);
const convertedRole = convert(fetchedRole);
Object.entries(convertedRole).map((entry) => {
form.setValue(entry[0], entry[1]);
});
setRole(convertedRole);
}
};
setTimeout(update, 100);
}, [key]);
const { fields, append, remove } = useFieldArray({
control: form.control,
name: "attributes",
});
useEffect(() => append({ key: "", value: "" }), [append, role]);
const save = async (role: RoleFormType) => {
try {
const { attributes, ...rest } = role;
const roleRepresentation: RoleRepresentation = rest;
if (id) {
if (attributes) {
roleRepresentation.attributes = arrayToAttributes(attributes);
}
if (!clientId) {
await adminClient.roles.updateById({ id }, roleRepresentation);
} else {
await adminClient.clients.updateRole(
{ id: clientId, roleName: role.name! },
roleRepresentation
);
}
await adminClient.roles.createComposite(
{ roleId: id, realm },
additionalRoles
);
setRole(role);
} else {
let createdRole;
if (!clientId) {
await adminClient.roles.create(roleRepresentation);
createdRole = await adminClient.roles.findOneByName({
name: role.name!,
});
} else {
await adminClient.clients.createRole({
id: clientId,
name: role.name,
});
if (role.description) {
await adminClient.clients.updateRole(
{ id: clientId, roleName: role.name! },
roleRepresentation
);
}
createdRole = await adminClient.clients.findRole({
id: clientId,
roleName: role.name!,
});
}
setRole(convert(createdRole));
history.push(
url.substr(0, url.lastIndexOf("/") + 1) + createdRole.id + "/details"
);
}
addAlert(t(id ? "roleSaveSuccess" : "roleCreated"), AlertVariant.success);
} catch (error) {
addAlert(
t((id ? "roleSave" : "roleCreate") + "Error", {
error: error.response.data?.errorMessage || error,
}),
AlertVariant.danger
);
}
};
const addComposites = async (composites: Composites[]): Promise<void> => {
const compositeArray = composites;
setAdditionalRoles([...additionalRoles, ...compositeArray]);
try {
await adminClient.roles.createComposite(
{ roleId: id, realm: realm },
compositeArray
);
history.push(url.substr(0, url.lastIndexOf("/") + 1) + "AssociatedRoles");
refresh();
addAlert(t("addAssociatedRolesSuccess"), AlertVariant.success);
} catch (error) {
addAlert(t("addAssociatedRolesError", { error }), AlertVariant.danger);
}
};
const [toggleDeleteDialog, DeleteConfirm] = useConfirmDialog({
titleKey: "roles:roleDeleteConfirm",
messageKey: t("roles:roleDeleteConfirmDialog", {
name: role?.name || t("createRole"),
}),
continueButtonLabel: "common:delete",
continueButtonVariant: ButtonVariant.danger,
onConfirm: async () => {
try {
if (!clientId) {
await adminClient.roles.delById({ id });
} else {
await adminClient.clients.delRole({
id: clientId,
roleName: role!.name as string,
});
}
addAlert(t("roleDeletedSuccess"), AlertVariant.success);
const loc = url.replace(/\/attributes/g, "");
history.replace(`${loc.substr(0, loc.lastIndexOf("/"))}`);
} catch (error) {
addAlert(`${t("roleDeleteError")} ${error}`, AlertVariant.danger);
}
},
});
2021-01-20 21:10:25 +00:00
const toggleModal = () => setOpen(!open);
return (
<>
<DeleteConfirm />
<AssociatedRolesModal
onConfirm={addComposites}
existingCompositeRoles={additionalRoles}
open={open}
toggleDialog={() => setOpen(!open)}
/>
<ViewHeader
titleKey={role?.name || t("createRole")}
subKey={id ? "" : "roles:roleCreateExplain"}
actionsDropdownId="roles-actions-dropdown"
dropdownItems={
id
? [
<DropdownItem
2021-01-27 20:22:26 +00:00
key="delete-role"
component="button"
onClick={() => toggleDeleteDialog()}
>
{t("deleteRole")}
</DropdownItem>,
2021-01-20 21:10:25 +00:00
<DropdownItem
2021-01-27 20:22:26 +00:00
key="toggle-modal"
id="add-roles"
2021-01-20 21:10:25 +00:00
component="button"
onClick={() => toggleModal()}
>
{t("addAssociatedRolesText")}
</DropdownItem>,
]
: undefined
}
/>
<PageSection variant="light">
{id && (
<KeycloakTabs isBox>
<Tab
eventKey="details"
title={<TabTitleText>{t("details")}</TabTitleText>}
>
2021-01-26 20:06:16 +00:00
<RealmRoleForm
reset={() => form.reset(role)}
form={form}
save={save}
editMode={true}
/>
</Tab>
{additionalRoles.length > 0 ? (
<Tab
eventKey="AssociatedRoles"
title={<TabTitleText>{t("associatedRolesText")}</TabTitleText>}
>
<AssociatedRolesTab additionalRoles={additionalRoles} />
</Tab>
) : null}
<Tab
eventKey="attributes"
title={<TabTitleText>{t("attributes")}</TabTitleText>}
>
<RoleAttributes
form={form}
save={save}
array={{ fields, append, remove }}
2021-01-26 20:06:16 +00:00
reset={() => form.reset(role)}
/>
</Tab>
</KeycloakTabs>
)}
2021-01-26 20:06:16 +00:00
{!id && (
<RealmRoleForm
reset={() => form.reset()}
form={form}
save={save}
editMode={false}
/>
)}
</PageSection>
</>
);
2021-01-26 20:06:16 +00:00
};