keycloak-scim/src/components/role-mapping/RoleMapping.tsx

264 lines
7 KiB
TypeScript
Raw Normal View History

import { useState } from "react";
import { useTranslation } from "react-i18next";
import {
AlertVariant,
Badge,
Button,
ButtonVariant,
Checkbox,
ToolbarItem,
} from "@patternfly/react-core";
2022-04-29 07:03:39 +00:00
import { cellWidth } from "@patternfly/react-table";
import type ClientRepresentation from "@keycloak/keycloak-admin-client/lib/defs/clientRepresentation";
import type RoleRepresentation from "@keycloak/keycloak-admin-client/lib/defs/roleRepresentation";
import type KeycloakAdminClient from "@keycloak/keycloak-admin-client";
import { AddRoleMappingModal } from "./AddRoleMappingModal";
import { KeycloakDataTable } from "../table-toolbar/KeycloakDataTable";
2022-05-02 05:51:09 +00:00
import { emptyFormatter, upperCaseFormatter } from "../../util";
import { useAlerts } from "../alert/Alerts";
import { useConfirmDialog } from "../confirm-dialog/ConfirmDialog";
import { useAdminClient } from "../../context/auth/AdminClient";
import { ListEmptyState } from "../list-empty-state/ListEmptyState";
import {
deleteMapping,
getEffectiveClientRoles,
getEffectiveRoles,
getMapping,
} from "./queries";
import "./role-mapping.css";
export type CompositeRole = RoleRepresentation & {
parent: RoleRepresentation;
isInherited?: boolean;
};
export type Row = {
client?: ClientRepresentation;
role: RoleRepresentation | CompositeRole;
};
export const mapRoles = (
2021-06-15 11:12:32 +00:00
assignedRoles: Row[],
effectiveRoles: Row[],
hide: boolean
2022-04-29 07:03:39 +00:00
) => [
...(hide
? assignedRoles.map((row) => ({
...row,
role: {
...row.role,
isInherited: false,
},
}))
: effectiveRoles.map((row) => ({
...row,
role: {
...row.role,
isInherited:
assignedRoles.find((r) => r.role.id === row.role.id) === undefined,
},
}))),
];
export const ServiceRole = ({ role, client }: Row) => (
<>
{client && (
2022-05-02 05:51:09 +00:00
<Badge isRead className="keycloak-admin--role-mapping__client-name">
{client.clientId}
</Badge>
)}
{role.name}
</>
);
export type ResourcesKey = keyof KeycloakAdminClient;
type RoleMappingProps = {
name: string;
id: string;
type: ResourcesKey;
isManager?: boolean;
save: (rows: Row[]) => Promise<void>;
};
export const RoleMapping = ({
name,
id,
type,
isManager = true,
save,
}: RoleMappingProps) => {
2022-04-05 15:02:27 +00:00
const { t } = useTranslation(type);
const { adminClient } = useAdminClient();
const { addAlert, addError } = useAlerts();
const [key, setKey] = useState(0);
const refresh = () => setKey(key + 1);
const [hide, setHide] = useState(true);
const [showAssign, setShowAssign] = useState(false);
const [selected, setSelected] = useState<Row[]>([]);
const assignRoles = async (rows: Row[]) => {
await save(rows);
refresh();
};
const loader = async () => {
const effectiveRoles = await getEffectiveRoles(adminClient, type, id);
let effectiveClientRoles: Row[] = [];
if (!hide) {
const clients = await adminClient.clients.find();
effectiveClientRoles = (
await Promise.all(
clients.map(async (client) =>
getEffectiveClientRoles(adminClient, type, id, client)
)
)
).flat();
}
const roles = await getMapping(adminClient, type, id);
const realmRoles = roles.realmMappings?.map((role) => ({ role }));
const client = Object.values(roles.clientMappings || {})
.map((client) =>
client.mappings.map((role: RoleRepresentation) => ({
client: { clientId: client.client, ...client },
role,
}))
)
.flat();
return [
...mapRoles(realmRoles || [], effectiveRoles, hide),
...[...client, ...effectiveClientRoles],
];
};
2022-05-11 09:43:07 +00:00
const [toggleDeleteDialog, DeleteConfirm] = useConfirmDialog({
titleKey: "clients:removeMappingTitle",
2022-04-05 15:02:27 +00:00
messageKey: t("clients:removeMappingConfirm", { count: selected.length }),
continueButtonLabel: "common:remove",
continueButtonVariant: ButtonVariant.danger,
onConfirm: async () => {
try {
await Promise.all(deleteMapping(adminClient, type, id, selected));
2022-05-11 09:43:07 +00:00
addAlert(t("clients:clientScopeRemoveSuccess"), AlertVariant.success);
refresh();
} catch (error) {
addError("clients:clientScopeRemoveError", error);
}
},
});
const ManagerToolbarItems = () => {
if (!isManager) return <span />;
return (
<>
<ToolbarItem>
<Button data-testid="assignRole" onClick={() => setShowAssign(true)}>
{t("common:assignRole")}
</Button>
</ToolbarItem>
<ToolbarItem>
<Button
variant="link"
data-testid="unAssignRole"
onClick={toggleDeleteDialog}
isDisabled={selected.length === 0}
>
{t("common:unAssignRole")}
</Button>
</ToolbarItem>
</>
);
};
return (
<>
{showAssign && (
<AddRoleMappingModal
id={id}
type={type}
name={name}
onAssign={assignRoles}
onClose={() => setShowAssign(false)}
/>
)}
<DeleteConfirm />
<KeycloakDataTable
data-testid="assigned-roles"
key={key}
loader={loader}
canSelectAll
onSelect={(rows) => setSelected(rows)}
searchPlaceholderKey="clients:searchByName"
ariaLabelKey="clients:clientScopeList"
isRowDisabled={(value) =>
(value.role as CompositeRole).isInherited || false
}
toolbarItem={
<>
<ToolbarItem>
<Checkbox
2022-04-05 15:02:27 +00:00
label={t("common:hideInheritedRoles")}
id="hideInheritedRoles"
isChecked={hide}
onChange={(check) => {
setHide(check);
refresh();
}}
/>
</ToolbarItem>
<ManagerToolbarItems />
</>
}
actions={
isManager
? [
{
title: t("common:unAssignRole"),
onRowClick: async (role) => {
setSelected([role]);
toggleDeleteDialog();
return false;
},
},
]
: []
}
columns={[
{
name: "role.name",
2022-04-05 15:02:27 +00:00
displayKey: t("common:name"),
2022-04-29 07:03:39 +00:00
transforms: [cellWidth(30)],
cellRenderer: ServiceRole,
},
2022-05-02 05:51:09 +00:00
{
name: "role.isInherited",
displayKey: t("common:inherent"),
cellFormatters: [upperCaseFormatter(), emptyFormatter()],
},
{
name: "role.description",
2022-04-05 15:02:27 +00:00
displayKey: t("common:description"),
cellFormatters: [emptyFormatter()],
},
]}
emptyState={
<ListEmptyState
message={t("noRoles")}
instructions={t("noRolesInstructions")}
2022-04-05 15:02:27 +00:00
primaryActionText={t("common:assignRole")}
onPrimaryAction={() => setShowAssign(true)}
/>
}
/>
</>
);
};