keycloak-scim/src/user/UsersSection.tsx

436 lines
13 KiB
TypeScript
Raw Normal View History

import {
AlertVariant,
Button,
ButtonVariant,
Dropdown,
DropdownItem,
EmptyState,
InputGroup,
KebabToggle,
Label,
PageSection,
2022-04-26 10:11:17 +00:00
Tab,
TabTitleText,
2021-08-25 14:48:11 +00:00
Text,
TextContent,
TextInput,
Toolbar,
ToolbarContent,
ToolbarItem,
Tooltip,
} from "@patternfly/react-core";
import {
ExclamationCircleIcon,
InfoCircleIcon,
SearchIcon,
WarningTriangleIcon,
} from "@patternfly/react-icons";
import type { IRowData } from "@patternfly/react-table";
import type RealmRepresentation from "@keycloak/keycloak-admin-client/lib/defs/realmRepresentation";
import type ComponentRepresentation from "@keycloak/keycloak-admin-client/lib/defs/componentRepresentation";
import type UserRepresentation from "@keycloak/keycloak-admin-client/lib/defs/userRepresentation";
import React, { useState } from "react";
import { useTranslation } from "react-i18next";
import { Link, useHistory } from "react-router-dom";
import { useAlerts } from "../components/alert/Alerts";
import { useConfirmDialog } from "../components/confirm-dialog/ConfirmDialog";
import { ListEmptyState } from "../components/list-empty-state/ListEmptyState";
import { KeycloakDataTable } from "../components/table-toolbar/KeycloakDataTable";
import { ViewHeader } from "../components/view-header/ViewHeader";
import { useAdminClient, useFetch } from "../context/auth/AdminClient";
import { useRealm } from "../context/realm-context/RealmContext";
import { emptyFormatter } from "../util";
import { toUser } from "./routes/User";
import { toAddUser } from "./routes/AddUser";
import helpUrls from "../help-urls";
import { KeycloakSpinner } from "../components/keycloak-spinner/KeycloakSpinner";
2022-04-26 10:11:17 +00:00
import { PermissionsTab } from "../components/permission-tab/PermissionTab";
import { toUsers, UserTab } from "./routes/Users";
import {
routableTab,
RoutableTabs,
} from "../components/routable-tabs/RoutableTabs";
import "./user-section.css";
type BruteUser = UserRepresentation & {
brute?: Record<string, object>;
};
2021-10-29 16:11:06 +00:00
export default function UsersSection() {
const { t } = useTranslation("users");
const adminClient = useAdminClient();
const { addAlert, addError } = useAlerts();
const { realm: realmName } = useRealm();
2021-03-03 13:53:42 +00:00
const history = useHistory();
const [userStorage, setUserStorage] = useState<ComponentRepresentation[]>();
const [searchUser, setSearchUser] = useState<string>();
const [realm, setRealm] = useState<RealmRepresentation | undefined>();
const [kebabOpen, setKebabOpen] = useState(false);
const [selectedRows, setSelectedRows] = useState<UserRepresentation[]>([]);
const [key, setKey] = useState(0);
2022-03-15 09:44:46 +00:00
const refresh = () => setKey(key + 1);
useFetch(
async () => {
const testParams = {
type: "org.keycloak.storage.UserStorageProvider",
};
try {
return await Promise.all([
adminClient.components.find(testParams),
adminClient.realms.findOne({ realm: realmName }),
]);
} catch {
return [[{}], undefined] as [
ComponentRepresentation[],
RealmRepresentation | undefined
];
}
},
([storageProviders, realm]) => {
setUserStorage(storageProviders);
setRealm(realm);
},
[]
);
const UserDetailLink = (user: UserRepresentation) => (
2021-08-26 12:15:28 +00:00
<Link
key={user.username}
to={toUser({ realm: realmName, id: user.id!, tab: "settings" })}
>
{user.username}
</Link>
);
const loader = async (first?: number, max?: number, search?: string) => {
const params: { [name: string]: string | number } = {
first: first!,
max: max!,
};
2021-08-25 14:48:11 +00:00
const searchParam = search || searchUser || "";
if (searchParam) {
params.search = searchParam;
}
if (!listUsers && !searchParam) {
return [];
}
2021-08-25 14:48:11 +00:00
try {
const users = await adminClient.users.find({
briefRepresentation: true,
...params,
});
if (realm?.bruteForceProtected) {
const brutes = await Promise.all(
users.map((user: BruteUser) =>
adminClient.attackDetection.findOne({
id: user.id!,
})
)
);
for (let index = 0; index < users.length; index++) {
const user: BruteUser = users[index];
user.brute = brutes[index];
}
}
return users;
} catch (error) {
2022-03-15 09:44:46 +00:00
if (userStorage?.length) {
addError("users:noUsersFoundErrorStorage", error);
} else {
addError("users:noUsersFoundError", error);
}
return [];
}
};
const [toggleUnlockUsersDialog, UnlockUsersConfirm] = useConfirmDialog({
titleKey: "users:unlockAllUsers",
messageKey: "users:unlockUsersConfirm",
continueButtonLabel: "users:unlock",
onConfirm: async () => {
try {
await adminClient.attackDetection.delAll();
refresh();
addAlert(t("unlockUsersSuccess"), AlertVariant.success);
} catch (error) {
addError("users:unlockUsersError", error);
}
},
});
const [toggleDeleteDialog, DeleteConfirm] = useConfirmDialog({
titleKey: "users:deleteConfirm",
messageKey: t("deleteConfirmDialog", { count: selectedRows.length }),
continueButtonLabel: "delete",
continueButtonVariant: ButtonVariant.danger,
onConfirm: async () => {
try {
for (const user of selectedRows) {
await adminClient.users.del({ id: user.id! });
}
setSelectedRows([]);
refresh();
addAlert(t("userDeletedSuccess"), AlertVariant.success);
} catch (error) {
addError("users:userDeletedError", error);
}
},
});
const StatusRow = (user: BruteUser) => {
return (
<>
{!user.enabled && (
<Label key={user.id} color="red" icon={<InfoCircleIcon />}>
{t("disabled")}
</Label>
)}
{user.brute?.disabled && (
<Label key={user.id} color="orange" icon={<WarningTriangleIcon />}>
{t("temporaryDisabled")}
</Label>
)}
{user.enabled && !user.brute?.disabled && "—"}
</>
);
};
const ValidatedEmail = (user: UserRepresentation) => {
return (
<>
{!user.emailVerified && (
<Tooltip
key={`email-verified-${user.id}`}
content={<>{t("notVerified")}</>}
>
<ExclamationCircleIcon className="keycloak__user-section__email-verified" />
</Tooltip>
)}{" "}
{emptyFormatter()(user.email)}
</>
);
};
const goToCreate = () => history.push(toAddUser({ realm: realmName }));
if (!userStorage) {
return <KeycloakSpinner />;
}
//should *only* list users when no user federation is configured
const listUsers = !(userStorage.length > 0);
const toolbar = (
<>
<ToolbarItem>
<Button data-testid="add-user" onClick={goToCreate}>
{t("addUser")}
</Button>
</ToolbarItem>
{!realm?.bruteForceProtected ? (
<ToolbarItem>
<Button
variant={ButtonVariant.plain}
onClick={toggleDeleteDialog}
data-testid="delete-user-btn"
isDisabled={selectedRows.length === 0}
>
{t("deleteUser")}
</Button>
</ToolbarItem>
) : (
<ToolbarItem>
<Dropdown
toggle={<KebabToggle onToggle={(open) => setKebabOpen(open)} />}
isOpen={kebabOpen}
isPlain
dropdownItems={[
<DropdownItem
key="deleteUser"
component="button"
isDisabled={selectedRows.length === 0}
onClick={() => {
toggleDeleteDialog();
setKebabOpen(false);
}}
>
{t("deleteUser")}
</DropdownItem>,
<DropdownItem
key="unlock"
component="button"
onClick={() => {
toggleUnlockUsersDialog();
setKebabOpen(false);
}}
>
{t("unlockAllUsers")}
</DropdownItem>,
]}
/>
</ToolbarItem>
)}
</>
);
2021-03-03 13:53:42 +00:00
2022-04-26 10:11:17 +00:00
const route = (tab: UserTab) =>
routableTab({
to: toUsers({
realm: realmName,
tab,
}),
history,
});
return (
<>
<DeleteConfirm />
<UnlockUsersConfirm />
<ViewHeader
titleKey="users:title"
subKey="users:usersExplain"
helpUrl={helpUrls.usersUrl}
2022-04-26 10:11:17 +00:00
divider={false}
/>
<PageSection
data-testid="users-page"
variant="light"
className="pf-u-p-0"
>
2022-04-26 10:11:17 +00:00
<RoutableTabs
data-testid="user-tabs"
defaultLocation={toUsers({
realm: realmName,
tab: "list",
})}
isBox
mountOnEnter
>
<Tab
id="list"
data-testid="listTab"
title={<TabTitleText>{t("userList")}</TabTitleText>}
{...route("list")}
>
<KeycloakDataTable
key={key}
loader={loader}
isPaginated
ariaLabelKey="users:title"
searchPlaceholderKey="users:searchForUser"
canSelectAll
onSelect={(rows) => setSelectedRows([...rows])}
emptyState={
!listUsers ? (
<>
<Toolbar>
<ToolbarContent>
<ToolbarItem>
<InputGroup>
<TextInput
name="search-input"
type="search"
aria-label={t("search")}
placeholder={t("users:searchForUser")}
onChange={(value) => {
setSearchUser(value);
}}
onKeyDown={(e) => {
if (e.key === "Enter") {
refresh();
}
}}
/>
<Button
variant={ButtonVariant.control}
aria-label={t("common:search")}
onClick={refresh}
>
<SearchIcon />
</Button>
</InputGroup>
</ToolbarItem>
{toolbar}
</ToolbarContent>
</Toolbar>
<EmptyState data-testid="empty-state" variant="large">
<TextContent className="kc-search-users-text">
<Text>{t("searchForUserDescription")}</Text>
</TextContent>
</EmptyState>
</>
) : (
<ListEmptyState
message={t("noUsersFound")}
instructions={t("emptyInstructions")}
primaryActionText={t("createNewUser")}
onPrimaryAction={goToCreate}
/>
)
}
toolbarItem={toolbar}
actionResolver={(rowData: IRowData) => {
const user: UserRepresentation = rowData.data;
if (!user.access?.manage) return [];
2022-04-26 10:11:17 +00:00
return [
{
title: t("common:delete"),
onClick: () => {
setSelectedRows([user]);
toggleDeleteDialog();
},
},
];
}}
columns={[
{
name: "username",
displayKey: "users:username",
cellRenderer: UserDetailLink,
},
{
name: "email",
displayKey: "users:email",
cellRenderer: ValidatedEmail,
},
2022-04-26 10:11:17 +00:00
{
name: "lastName",
displayKey: "users:lastName",
cellFormatters: [emptyFormatter()],
},
{
name: "firstName",
displayKey: "users:firstName",
cellFormatters: [emptyFormatter()],
},
{
name: "status",
displayKey: "users:status",
cellRenderer: StatusRow,
},
]}
/>
</Tab>
<Tab
id="permissions"
data-testid="permissionsTab"
title={<TabTitleText>{t("common:permissions")}</TabTitleText>}
{...route("permissions")}
>
<PermissionsTab type="users" />
</Tab>
</RoutableTabs>
</PageSection>
</>
);
2021-10-29 16:11:06 +00:00
}