diff --git a/src/realm-settings/NewClientPolicyForm.tsx b/src/realm-settings/NewClientPolicyForm.tsx index 6d1d3f250a..e4cbca9c44 100644 --- a/src/realm-settings/NewClientPolicyForm.tsx +++ b/src/realm-settings/NewClientPolicyForm.tsx @@ -20,7 +20,7 @@ import { useTranslation } from "react-i18next"; import { useForm } from "react-hook-form"; import { FormAccess } from "../components/form-access/FormAccess"; import { ViewHeader } from "../components/view-header/ViewHeader"; -import { Link, useHistory } from "react-router-dom"; +import { Link, useHistory, useParams } from "react-router-dom"; import { useRealm } from "../context/realm-context/RealmContext"; import { useAlerts } from "../components/alert/Alerts"; import { useAdminClient, useFetch } from "../context/auth/AdminClient"; @@ -31,6 +31,7 @@ import "./RealmSettingsSection.css"; import { useConfirmDialog } from "../components/confirm-dialog/ConfirmDialog"; import type ClientPolicyRepresentation from "@keycloak/keycloak-admin-client/lib/defs/clientPolicyRepresentation"; import { toClientPolicies } from "./routes/ClientPolicies"; +import type { EditClientPolicyParams } from "./routes/EditClientPolicy"; type NewClientPolicyForm = Required; @@ -44,15 +45,11 @@ const defaultValues: NewClientPolicyForm = { export const NewClientPolicyForm = () => { const { t } = useTranslation("realm-settings"); - const { - register, - errors, - handleSubmit, - reset: resetForm, - } = useForm({ + const { errors, reset: resetForm } = useForm({ defaultValues, }); const { realm } = useRealm(); + const { policyName } = useParams(); const { addAlert, addError } = useAlerts(); const adminClient = useAdminClient(); const [policies, setPolicies] = useState([]); @@ -65,23 +62,46 @@ export const NewClientPolicyForm = () => { useState(); const history = useHistory(); + const form = useForm({ mode: "onChange" }); useFetch( () => adminClient.clientPolicies.listPolicies(), (policies) => { setPolicies(policies.policies ?? []); + const currentPolicy = policies.policies?.find( + (item) => item.name === policyName + ); + if (currentPolicy) { + setupForm(currentPolicy); + } }, [] ); - const save = async (form: NewClientPolicyForm) => { + const setupForm = (policy: ClientPolicyRepresentation) => { + resetForm(); + Object.entries(policy).map(([key, value]) => { + form.setValue(key, value); + }); + }; + + const save = async () => { + const createdForm = form.getValues(); const createdPolicy = { - ...form, + ...createdForm, profiles: [], conditions: [], }; - const allPolicies = policies.concat(createdPolicy); + const policyNameExists = policies.find( + (policy) => policy.name === createdPolicy.name + ); + + const res = policies.map((policy) => + policy.name === createdPolicy.name ? createdPolicy : policy + ); + + const allPolicies = policyNameExists ? res : policies.concat(createdForm); try { await adminClient.clientPolicies.updatePolicy({ @@ -125,8 +145,8 @@ export const NewClientPolicyForm = () => { { } > {