keycloak-scim/src/events/AdminEvents.tsx

645 lines
20 KiB
TypeScript
Raw Normal View History

2020-12-11 14:48:39 +00:00
import {
ActionGroup,
2020-12-11 14:48:39 +00:00
Button,
Chip,
ChipGroup,
Dropdown,
DropdownToggle,
Flex,
FlexItem,
Form,
FormGroup,
2020-12-11 14:48:39 +00:00
Modal,
ModalVariant,
Select,
SelectOption,
SelectVariant,
TextInput,
Tooltip,
2020-12-11 14:48:39 +00:00
} from "@patternfly/react-core";
import {
cellWidth,
2020-12-11 14:48:39 +00:00
Table,
TableBody,
TableHeader,
TableVariant,
} from "@patternfly/react-table";
import { CodeEditor, Language } from "@patternfly/react-code-editor";
import type AdminEventRepresentation from "@keycloak/keycloak-admin-client/lib/defs/adminEventRepresentation";
import moment from "moment";
import React, { FunctionComponent, useMemo, useState } from "react";
import { Controller, useForm } from "react-hook-form";
import { useTranslation } from "react-i18next";
import { Link } from "react-router-dom";
import { pickBy } from "lodash";
2020-12-11 14:48:39 +00:00
import { ListEmptyState } from "../components/list-empty-state/ListEmptyState";
import { KeycloakDataTable } from "../components/table-toolbar/KeycloakDataTable";
import { useAdminClient } from "../context/auth/AdminClient";
import { useRealm } from "../context/realm-context/RealmContext";
import { useServerInfo } from "../context/server-info/ServerInfoProvider";
import "./events.css";
2020-12-11 14:48:39 +00:00
type DisplayDialogProps = {
titleKey: string;
onClose: () => void;
};
type AdminEventSearchForm = {
resourceTypes: string[];
operationTypes: string[];
resourcePath: string;
dateFrom: string;
dateTo: string;
authClient: string;
authUser: string;
authRealm: string;
authIpAddress: string;
};
const defaultValues: AdminEventSearchForm = {
resourceTypes: [],
operationTypes: [],
resourcePath: "",
dateFrom: "",
dateTo: "",
authClient: "",
authUser: "",
authRealm: "",
authIpAddress: "",
};
const DisplayDialog: FunctionComponent<DisplayDialogProps> = ({
titleKey,
onClose,
children,
}) => {
2020-12-11 14:48:39 +00:00
const { t } = useTranslation("events");
return (
<Modal
variant={ModalVariant.medium}
title={t(titleKey)}
isOpen={true}
onClose={onClose}
>
{children}
</Modal>
);
};
const MAX_TEXT_LENGTH = 38;
const Truncate = ({
text,
children,
}: {
text?: string;
children: (text: string) => any;
}) => {
const definedText = text || "";
const needsTruncation = definedText.length > MAX_TEXT_LENGTH;
const truncatedText = definedText.substr(0, MAX_TEXT_LENGTH);
return (
<>
{needsTruncation && (
<Tooltip content={text}>{children(truncatedText + "...")}</Tooltip>
)}
{!needsTruncation && <>{children(definedText)}</>}
</>
);
};
2020-12-11 14:48:39 +00:00
export const AdminEvents = () => {
const { t } = useTranslation("events");
const adminClient = useAdminClient();
const { realm } = useRealm();
const serverInfo = useServerInfo();
const resourceTypes = serverInfo.enums?.["resourceType"];
const operationTypes = serverInfo.enums?.["operationType"];
2020-12-11 14:48:39 +00:00
const [key, setKey] = useState(0);
const [searchDropdownOpen, setSearchDropdownOpen] = useState(false);
const [selectResourceTypesOpen, setSelectResourceTypesOpen] = useState(false);
const [selectOperationTypesOpen, setSelectOperationTypesOpen] =
useState(false);
const [activeFilters, setActiveFilters] = useState<
Partial<AdminEventSearchForm>
>({});
2020-12-11 14:48:39 +00:00
const [authEvent, setAuthEvent] = useState<AdminEventRepresentation>();
const [representationEvent, setRepresentationEvent] =
useState<AdminEventRepresentation>();
2020-12-11 14:48:39 +00:00
const filterLabels: Record<keyof AdminEventSearchForm, string> = {
resourceTypes: t("resourceTypes"),
operationTypes: t("operationTypes"),
resourcePath: t("resourcePath"),
dateFrom: t("dateFrom"),
dateTo: t("dateTo"),
authClient: t("client"),
authUser: t("userId"),
authRealm: t("realm"),
authIpAddress: t("ipAddress"),
};
const {
getValues,
register,
reset,
formState: { isDirty },
control,
} = useForm<AdminEventSearchForm>({
shouldUnregister: false,
mode: "onChange",
defaultValues,
});
function loader(first?: number, max?: number) {
return adminClient.realms.findAdminEvents({
// The admin client wants 'dateFrom' and 'dateTo' to be Date objects, however it cannot actually handle them so we need to cast to any.
...(activeFilters as any),
2020-12-11 14:48:39 +00:00
realm,
first,
max,
});
}
function submitSearch() {
setSearchDropdownOpen(false);
commitFilters();
}
function removeFilter(key: keyof AdminEventSearchForm) {
const formValues: AdminEventSearchForm = { ...getValues() };
delete formValues[key];
reset({ ...defaultValues, ...formValues });
commitFilters();
}
function removeFilterValue(
key: keyof AdminEventSearchForm,
valueToRemove: string
) {
const formValues = getValues();
const fieldValue = formValues[key];
const newFieldValue = Array.isArray(fieldValue)
? fieldValue.filter((val) => val !== valueToRemove)
: fieldValue;
reset({ ...formValues, [key]: newFieldValue });
commitFilters();
}
function commitFilters() {
const newFilters: Partial<AdminEventSearchForm> = pickBy(
getValues(),
(value) => value !== "" || (Array.isArray(value) && value.length > 0)
);
setActiveFilters(newFilters);
setKey(key + 1);
}
function refresh() {
commitFilters();
}
2020-12-11 14:48:39 +00:00
const LinkResource = (row: AdminEventRepresentation) => (
2021-08-26 12:15:28 +00:00
<Truncate text={row.resourcePath}>
{(text) => (
<>
{row.resourceType !== "COMPONENT" && (
<Link
to={`/${realm}/${row.resourcePath}${
row.resourceType !== "GROUP" ? "/settings" : ""
}`}
>
{text}
</Link>
)}
{row.resourceType === "COMPONENT" && <span>{text}</span>}
</>
)}
</Truncate>
);
const adminEventSearchFormDisplay = () => {
return (
2021-08-26 12:15:28 +00:00
<Flex
direction={{ default: "column" }}
spaceItems={{ default: "spaceItemsNone" }}
>
<FlexItem>
<Dropdown
id="admin-events-search-select"
data-testid="AdminEventsSearchSelector"
className="pf-u-ml-md"
toggle={
<DropdownToggle
data-testid="adminEventsSearchSelectorToggle"
onToggle={(isOpen) => setSearchDropdownOpen(isOpen)}
className="keycloak__events_search_selector_dropdown__toggle"
>
{t("searchForAdminEvent")}
</DropdownToggle>
}
isOpen={searchDropdownOpen}
>
<Form
isHorizontal
className="keycloak__events_search__form"
2021-08-26 12:15:28 +00:00
data-testid="searchForm"
>
2021-08-26 12:15:28 +00:00
<FormGroup
label={t("resourceTypes")}
fieldId="kc-resourceTypes"
className="keycloak__events_search__form_label"
>
<Controller
name="resourceTypes"
control={control}
render={({
onChange,
value,
}: {
onChange: (newValue: string[]) => void;
value: string[];
}) => (
<Select
className="keycloak__events_search__type_select"
name="resourceTypes"
data-testid="resource-types-searchField"
chipGroupProps={{
numChips: 1,
expandedText: "Hide",
collapsedText: "Show ${remaining}",
}}
variant={SelectVariant.typeaheadMulti}
typeAheadAriaLabel="Select"
onToggle={(isOpen) => setSelectResourceTypesOpen(isOpen)}
selections={value}
onSelect={(_, selectedValue) => {
const option = selectedValue.toString();
const changedValue = value.includes(option)
? value.filter((item) => item !== option)
: [...value, option];
onChange(changedValue);
}}
onClear={(resource) => {
resource.stopPropagation();
onChange([]);
}}
isOpen={selectResourceTypesOpen}
aria-labelledby={"resourceTypes"}
chipGroupComponent={
<ChipGroup>
{value.map((chip) => (
<Chip
key={chip}
onClick={(resource) => {
resource.stopPropagation();
onChange(value.filter((val) => val !== chip));
}}
>
{chip}
</Chip>
))}
</ChipGroup>
}
>
{resourceTypes?.map((option) => (
<SelectOption key={option} value={option} />
))}
</Select>
)}
/>
2021-08-26 12:15:28 +00:00
</FormGroup>
<FormGroup
label={t("operationTypes")}
fieldId="kc-operationTypes"
className="keycloak__events_search__form_label"
2021-08-26 12:15:28 +00:00
>
<Controller
name="operationTypes"
control={control}
render={({
onChange,
value,
}: {
onChange: (newValue: string[]) => void;
value: string[];
}) => (
<Select
className="keycloak__events_search__type_select"
name="operationTypes"
data-testid="operation-types-searchField"
chipGroupProps={{
numChips: 1,
expandedText: "Hide",
collapsedText: "Show ${remaining}",
}}
variant={SelectVariant.typeaheadMulti}
typeAheadAriaLabel="Select"
onToggle={(isOpen) => setSelectOperationTypesOpen(isOpen)}
selections={value}
onSelect={(_, selectedValue) => {
const option = selectedValue.toString();
const changedValue = value.includes(option)
? value.filter((item) => item !== option)
: [...value, option];
onChange(changedValue);
}}
onClear={(operation) => {
operation.stopPropagation();
onChange([]);
}}
isOpen={selectOperationTypesOpen}
aria-labelledby={"operationTypes"}
chipGroupComponent={
<ChipGroup>
{value.map((chip) => (
<Chip
key={chip}
onClick={(operation) => {
operation.stopPropagation();
onChange(value.filter((val) => val !== chip));
}}
>
{chip}
</Chip>
))}
</ChipGroup>
}
>
{operationTypes?.map((option) => (
<SelectOption key={option} value={option} />
))}
</Select>
)}
/>
2021-08-26 12:15:28 +00:00
</FormGroup>
<FormGroup
label={t("resourcePath")}
fieldId="kc-resourcePath"
2021-08-26 12:15:28 +00:00
className="keycloak__events_search__form_label"
>
<TextInput
ref={register()}
type="text"
id="kc-resourcePath"
name="resourcePath"
data-testid="resourcePath-searchField"
2021-08-26 12:15:28 +00:00
/>
</FormGroup>
<FormGroup
label={t("realm")}
fieldId="kc-realm"
className="keycloak__events_search__form_label"
>
<TextInput
ref={register()}
type="text"
id="kc-realm"
name="authRealm"
data-testid="realm-searchField"
/>
</FormGroup>
<FormGroup
label={t("client")}
fieldId="kc-client"
className="keycloak__events_search__form_label"
>
<TextInput
ref={register()}
type="text"
id="kc-client"
name="authClient"
data-testid="client-searchField"
/>
</FormGroup>
<FormGroup
label={t("user")}
fieldId="kc-user"
className="keycloak__events_search__form_label"
>
<TextInput
ref={register()}
type="text"
id="kc-user"
name="authUser"
data-testid="user-searchField"
/>
2021-08-26 12:15:28 +00:00
</FormGroup>
<FormGroup
label={t("ipAddress")}
fieldId="kc-ipAddress"
className="keycloak__events_search__form_label"
>
<TextInput
ref={register()}
type="text"
id="kc-ipAddress"
name="authIpAddress"
2021-08-26 12:15:28 +00:00
data-testid="ipAddress-searchField"
/>
</FormGroup>
<FormGroup
label={t("dateFrom")}
fieldId="kc-dateFrom"
className="keycloak__events_search__form_label"
>
<TextInput
ref={register()}
type="text"
id="kc-dateFrom"
name="dateFrom"
className="pf-c-form-control pf-m-icon pf-m-calendar"
placeholder="yyyy-MM-dd"
data-testid="dateFrom-searchField"
/>
</FormGroup>
<FormGroup
label={t("dateTo")}
fieldId="kc-dateTo"
className="keycloak__events_search__form_label"
>
<TextInput
ref={register()}
type="text"
id="kc-dateTo"
name="dateTo"
className="pf-c-form-control pf-m-icon pf-m-calendar"
placeholder="yyyy-MM-dd"
data-testid="dateTo-searchField"
/>
</FormGroup>
<ActionGroup>
<Button
className="keycloak__user_events_search__form_btn"
2021-08-26 12:15:28 +00:00
variant={"primary"}
onClick={submitSearch}
2021-08-26 12:15:28 +00:00
data-testid="search-events-btn"
isDisabled={!isDirty}
>
2021-08-26 12:15:28 +00:00
{t("searchAdminEventsBtn")}
</Button>
</ActionGroup>
</Form>
</Dropdown>
<Button
className="pf-u-ml-md"
onClick={refresh}
data-testid="refresh-btn"
>
{t("refresh")}
</Button>
</FlexItem>
<FlexItem>
{Object.entries(activeFilters).length > 0 && (
<div className="keycloak__searchChips pf-u-ml-md">
{Object.entries(activeFilters).map((filter) => {
const [key, value] = filter as [
keyof AdminEventSearchForm,
string | string[]
];
return (
<ChipGroup
className="pf-u-mt-md pf-u-mr-md"
key={key}
categoryName={filterLabels[key]}
isClosable
onClick={() => removeFilter(key)}
>
{typeof value === "string" ? (
<Chip isReadOnly>{value}</Chip>
) : (
value.map((entry) => (
<Chip
key={entry}
onClick={() => removeFilterValue(key, entry)}
>
{entry}
</Chip>
))
)}
</ChipGroup>
);
})}
</div>
)}
</FlexItem>
2021-08-26 12:15:28 +00:00
</Flex>
);
};
const rows = [
[t("realm"), authEvent?.authDetails?.realmId],
[t("client"), authEvent?.authDetails?.clientId],
[t("user"), authEvent?.authDetails?.userId],
[t("ipAddress"), authEvent?.authDetails?.ipAddress],
];
function prettyPrintJSON(json: string) {
try {
return JSON.stringify(JSON.parse(json), null, 2);
} catch (error) {
return json;
}
}
const code = useMemo(
() =>
prettyPrintJSON(
representationEvent?.representation
? prettyPrintJSON(representationEvent.representation)
: ""
),
[representationEvent?.representation]
);
2020-12-11 14:48:39 +00:00
return (
<>
{authEvent && (
<DisplayDialog titleKey="auth" onClose={() => setAuthEvent(undefined)}>
<Table
aria-label="authData"
data-testid="auth-dialog"
2020-12-11 14:48:39 +00:00
variant={TableVariant.compact}
cells={[t("attribute"), t("value")]}
rows={rows}
2020-12-11 14:48:39 +00:00
>
<TableHeader />
<TableBody />
</Table>
</DisplayDialog>
)}
{representationEvent && (
<DisplayDialog
titleKey="representation"
data-testid="representation-dialog"
2020-12-11 14:48:39 +00:00
onClose={() => setRepresentationEvent(undefined)}
>
<CodeEditor
isLineNumbersVisible
isReadOnly
code={code}
language={Language.json}
height="125px"
/>
2020-12-11 14:48:39 +00:00
</DisplayDialog>
)}
<KeycloakDataTable
2020-12-11 14:48:39 +00:00
key={key}
loader={loader}
isPaginated
2020-12-11 17:25:54 +00:00
ariaLabelKey="events:adminEvents"
toolbarItem={adminEventSearchFormDisplay()}
2020-12-11 14:48:39 +00:00
actions={[
{
title: t("auth"),
onRowClick: (event) => setAuthEvent(event),
},
{
title: t("representation"),
onRowClick: (event) => setRepresentationEvent(event),
},
]}
columns={[
{
name: "time",
displayKey: "events:time",
cellRenderer: (row) => moment(row.time).format("LLL"),
2020-12-11 14:48:39 +00:00
},
{
name: "resourcePath",
displayKey: "events:resourcePath",
cellRenderer: LinkResource,
2020-12-11 14:48:39 +00:00
},
{
name: "resourceType",
displayKey: "events:resourceType",
},
{
name: "operationType",
displayKey: "events:operationType",
transforms: [cellWidth(10)],
2020-12-11 14:48:39 +00:00
},
{
name: "",
displayKey: "events:user",
cellRenderer: (event) => event.authDetails?.userId,
},
]}
emptyState={
<ListEmptyState
message={t("emptyEvents")}
instructions={t("emptyEventsInstructions")}
/>
}
/>
</>
);
};