From 27500667a39178ae6e694b486756a54c6508b9a4 Mon Sep 17 00:00:00 2001 From: "DESKTOP-1R2VSQH\\Lenovo ThinkPad E490" Date: Wed, 29 May 2024 16:17:53 +0700 Subject: [PATCH] keycloak get role --- src/controllers/UserController.ts | 22 +++++++++++++++++++--- src/keycloak/index.ts | 25 +++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 3 deletions(-) diff --git a/src/controllers/UserController.ts b/src/controllers/UserController.ts index 935223fd..4e520dd4 100644 --- a/src/controllers/UserController.ts +++ b/src/controllers/UserController.ts @@ -27,6 +27,7 @@ import { getUserList, removeUserGroup, removeUserRoles, + getRoleMappings, } from "../keycloak"; // import * as io from "../lib/websocket"; // import elasticsearch from "../elasticsearch"; @@ -46,9 +47,25 @@ function stripLeadingSlash(str: string) { @Security("bearerAuth") export class KeycloakController extends Controller { @Get("user/{id}") - async getUser(@Path() id: string) { - return await getUser(id); + async getUser(@Path("id") id: string) { + const userData = await getUser(id); + if (!userData) { + throw new Error("User not found"); + } + const rolesData = await getRoleMappings(id); + if (!rolesData) { + throw new Error("Role mappings not found"); + } + const userDataWithRoles = { + ...userData, + roles: rolesData, + }; + + return userDataWithRoles; } + // async getUser(@Path() id: string) { + // return await getUser(id); + // } @Post("user") @Security("bearerAuth", ["system", "admin"]) @@ -134,7 +151,6 @@ export class KeycloakController extends Controller { if (!result) throw new Error("Failed. Cannot delete userId."); } // @Security("bearerAuth", ["system", "admin"]) - @Get("role") async getRole() { diff --git a/src/keycloak/index.ts b/src/keycloak/index.ts index 61d54851..0ff5edb9 100644 --- a/src/keycloak/index.ts +++ b/src/keycloak/index.ts @@ -206,6 +206,31 @@ export async function deleteUser(userId: string) { return true; } +/** + * Get keycloak user by uuid + * + * Client must have permission to manage realm's user + * + * @returns user if success, false otherwise. + */ +export async function getRoleMappings(userId: string) { + const res = await fetch( + `${KC_URL}/admin/realms/${KC_REALM}/users/${userId}/role-mappings/realm`, + { + headers: { + authorization: `Bearer ${await getToken()}`, + "content-type": `application/json`, + }, + }, + ).catch((e) => console.log("Keycloak Error: ", e)); + if (!res) return false; + if (!res.ok) { + return Boolean(console.error("Keycloak Error Response: ", await res.json())); + } + + return await res.json(); +} + /** * Get roles list or specific role data *