diff --git a/src/keycloak/index.ts b/src/keycloak/index.ts index b661450c..5fd89ff7 100644 --- a/src/keycloak/index.ts +++ b/src/keycloak/index.ts @@ -379,6 +379,20 @@ export async function getUserCountOrg(first = "", max = "", search = "", userIds export async function editUser(userId: string, opts: Record) { const { password, ...rest } = opts; + // Get existing user data to preserve other fields + const existingUser = await getUser(userId); + if (!existingUser) { + console.error(`[editUser] User ${userId} not found in Keycloak`); + return false; + } + + // Merge existing user data with updated fields + const updatedUser = { + ...existingUser, + ...rest, + credentials: (password && [{ type: "password", value: opts?.password }]) || undefined, + }; + const res = await fetch(`${KC_URL}/admin/realms/${KC_REALMS}/users/${userId}`, { // prettier-ignore headers: { @@ -386,11 +400,7 @@ export async function editUser(userId: string, opts: Record) { "content-type": `application/json`, }, method: "PUT", - body: JSON.stringify({ - enabled: true, - credentials: (password && [{ type: "password", value: opts?.password }]) || undefined, - ...rest, - }), + body: JSON.stringify(updatedUser), }).catch((e) => console.log("Keycloak Error: ", e)); if (!res) return false; @@ -419,6 +429,24 @@ export async function updateName( ) { // const { password, ...rest } = opts; + // Get existing user data to preserve other fields + const existingUser = await getUser(userId); + if (!existingUser) { + console.error(`[updateName] User ${userId} not found in Keycloak`); + return false; + } + + // Merge existing user data with updated name fields + const updatedUser = { + ...existingUser, + firstName, + lastName, + attributes: { + ...(existingUser.attributes || {}), + prefix, + }, + }; + const res = await fetch(`${KC_URL}/admin/realms/${KC_REALMS}/users/${userId}`, { // prettier-ignore headers: { @@ -426,16 +454,7 @@ export async function updateName( "content-type": `application/json`, }, method: "PUT", - body: JSON.stringify({ - enabled: true, - // credentials: (password && [{ type: "password", value: opts?.password }]) || undefined, - // ...rest, - firstName, - lastName, - attributes: { - prefix, - }, - }), + body: JSON.stringify(updatedUser), }).catch((e) => console.log("Keycloak Error: ", e)); if (!res) return false;