import React, { useEffect, useState } from "react";
import {
Alert,
AlertVariant,
ButtonVariant,
Divider,
DropdownItem,
PageSection,
Spinner,
Tab,
Tabs,
TabTitleText,
} from "@patternfly/react-core";
import { useParams } from "react-router-dom";
import { useErrorHandler } from "react-error-boundary";
import { useTranslation } from "react-i18next";
import { Controller, FormProvider, useForm } from "react-hook-form";
import ClientRepresentation from "keycloak-admin/lib/defs/clientRepresentation";
import _ from "lodash";
import { ClientSettings } from "./ClientSettings";
import { useAlerts } from "../components/alert/Alerts";
import {
ConfirmDialogModal,
useConfirmDialog,
} from "../components/confirm-dialog/ConfirmDialog";
import { DownloadDialog } from "../components/download-dialog/DownloadDialog";
import { ViewHeader } from "../components/view-header/ViewHeader";
import { useAdminClient, asyncStateFetch } from "../context/auth/AdminClient";
import { Credentials } from "./credentials/Credentials";
import {
convertFormValuesToObject,
convertToFormValues,
exportClient,
} from "../util";
import {
convertToMultiline,
MultiLine,
toValue,
} from "../components/multi-line-input/MultiLineInput";
import { ClientScopes } from "./scopes/ClientScopes";
import { EvaluateScopes } from "./scopes/EvaluateScopes";
import { RolesList } from "../realm-roles/RolesList";
import { ServiceAccount } from "./service-account/ServiceAccount";
import { KeycloakTabs } from "../components/keycloak-tabs/KeycloakTabs";
import { AdvancedTab } from "./AdvancedTab";
type ClientDetailHeaderProps = {
onChange: (value: boolean) => void;
value: boolean;
save: () => void;
client: ClientRepresentation;
toggleDownloadDialog: () => void;
toggleDeleteDialog: () => void;
};
const ClientDetailHeader = ({
onChange,
value,
save,
client,
toggleDownloadDialog,
toggleDeleteDialog,
}: ClientDetailHeaderProps) => {
const { t } = useTranslation("clients");
const [toggleDisableDialog, DisableConfirm] = useConfirmDialog({
titleKey: "clients:disableConfirmTitle",
messageKey: "clients:disableConfirm",
continueButtonLabel: "common:disable",
onConfirm: () => {
onChange(!value);
save();
},
});
return (
<>
toggleDownloadDialog()}>
{t("downloadAdapterConfig")}
,
exportClient(client)}>
{t("common:export")}
,
,
toggleDeleteDialog()}>
{t("common:delete")}
,
]}
isEnabled={value}
onToggle={(value) => {
if (!value) {
toggleDisableDialog();
} else {
onChange(value);
save();
}
}}
/>
>
);
};
export type ClientForm = Omit<
ClientRepresentation,
"redirectUris" | "webOrigins"
> & {
redirectUris: MultiLine[];
webOrigins: MultiLine[];
};
export type SaveOptions = {
confirmed?: boolean;
messageKey?: string;
};
export const ClientDetails = () => {
const { t } = useTranslation("clients");
const adminClient = useAdminClient();
const handleError = useErrorHandler();
const { addAlert } = useAlerts();
const [downloadDialogOpen, setDownloadDialogOpen] = useState(false);
const toggleDownloadDialog = () => setDownloadDialogOpen(!downloadDialogOpen);
const [changeAuthenticatorOpen, setChangeAuthenticatorOpen] = useState(false);
const toggleChangeAuthenticator = () =>
setChangeAuthenticatorOpen(!changeAuthenticatorOpen);
const [activeTab2, setActiveTab2] = useState(30);
const form = useForm();
const { clientId } = useParams<{ clientId: string }>();
const [client, setClient] = useState();
const loader = async () => {
const roles = await adminClient.clients.listRoles({ id: clientId });
return _.sortBy(roles, (role) => role.name?.toUpperCase());
};
const [toggleDeleteDialog, DeleteConfirm] = useConfirmDialog({
titleKey: "clients:clientDeleteConfirmTitle",
messageKey: "clients:clientDeleteConfirm",
continueButtonLabel: "common:delete",
continueButtonVariant: ButtonVariant.danger,
onConfirm: async () => {
try {
await adminClient.clients.del({ id: clientId });
addAlert(t("clientDeletedSuccess"), AlertVariant.success);
} catch (error) {
addAlert(`${t("clientDeleteError")} ${error}`, AlertVariant.danger);
}
},
});
const setupForm = (client: ClientRepresentation) => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { redirectUris, webOrigins, ...formValues } = client;
form.reset(formValues);
Object.entries(client).map((entry) => {
if (entry[0] === "redirectUris" || entry[0] === "webOrigins") {
form.setValue(entry[0], convertToMultiline(entry[1]));
} else if (entry[0] === "attributes") {
convertToFormValues(entry[1], "attributes", form.setValue);
} else {
form.setValue(entry[0], entry[1]);
}
});
};
useEffect(() => {
return asyncStateFetch(
() => adminClient.clients.findOne({ id: clientId }),
(fetchedClient) => {
setClient(fetchedClient);
setupForm(fetchedClient);
},
handleError
);
}, [clientId]);
const save = async (
{ confirmed = false, messageKey = "clientSaveSuccess" }: SaveOptions = {
confirmed: false,
messageKey: "clientSaveSuccess",
}
) => {
if (await form.trigger()) {
if (
client?.publicClient &&
client?.clientAuthenticatorType !==
form.getValues("clientAuthenticatorType") &&
!confirmed
) {
toggleChangeAuthenticator();
return;
}
const redirectUris = toValue(form.getValues()["redirectUris"]);
const webOrigins = toValue(form.getValues()["webOrigins"]);
const attributes = convertFormValuesToObject(
form.getValues()["attributes"]
);
try {
const newClient: ClientRepresentation = {
...client,
...form.getValues(),
redirectUris,
webOrigins,
attributes,
};
await adminClient.clients.update({ id: clientId }, newClient);
setupForm(newClient);
setClient(newClient);
addAlert(t(messageKey), AlertVariant.success);
} catch (error) {
addAlert(`${t("clientSaveError")} '${error}'`, AlertVariant.danger);
}
}
};
if (!client) {
return (
);
}
return (
<>
save({ confirmed: true })}
>
<>
{t("changeAuthenticatorConfirm", {
clientAuthenticatorType: form.getValues("clientAuthenticatorType"),
})}
{form.getValues("clientAuthenticatorType") === "client-jwt" && (
)}
>
(
)}
/>
{t("common:settings")}}
>
save()}
reset={() => setupForm(client)}
/>
{client.publicClient && (
{t("credentials")}}
>
save()} />
)}
{t("roles")}}
>
{t("clientScopes")}}
>
setActiveTab2(key as number)}
>
{t("setup")}}
>
{t("evaluate")}}
>
{client!.serviceAccountsEnabled && (
{t("serviceAccount")}}
>
)}
{t("advanced")}}
>
>
);
};