import { NextResponse } from "next/server"; import { getServerSession } from "next-auth"; import { authOptions } from "@/app/api/auth/[...nextauth]/route"; import { getKeycloakAdminClient } from "@/lib/keycloak"; import { RoleRepresentation } from "@keycloak/keycloak-admin-client/lib/defs/roleRepresentation"; export async function GET( request: Request, { params }: { params: { userId: string } } ) { try { const session = await getServerSession(authOptions); if (!session) { return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); } const { userId } = params; const kcAdminClient = await getKeycloakAdminClient(); // Get all available roles const availableRoles = await kcAdminClient.roles.find(); // Get user's current roles const userRoles = await kcAdminClient.users.listRoleMappings({ id: userId, }); return NextResponse.json({ availableRoles, userRoles, }); } catch (error) { console.error("Error fetching roles:", error); return NextResponse.json( { error: "Failed to fetch roles" }, { status: 500 } ); } } export async function PUT( request: Request, { params }: { params: { userId: string } } ) { try { const session = await getServerSession(authOptions); if (!session) { return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); } const { userId } = params; const { roles } = await request.json(); const kcAdminClient = await getKeycloakAdminClient(); // Get all available roles const availableRoles = await kcAdminClient.roles.find(); // Get current user roles const currentRoles = await kcAdminClient.users.listRoleMappings({ id: userId, }); // Find roles to add and remove const rolesToAdd = roles.filter( (role: string) => !currentRoles.realmMappings?.some((r: RoleRepresentation) => r.name === role) ); const rolesToRemove = currentRoles.realmMappings?.filter( (role: RoleRepresentation) => !roles.includes(role.name) ); // Add new roles for (const roleName of rolesToAdd) { const role = availableRoles.find((r: RoleRepresentation) => r.name === roleName); if (role) { await kcAdminClient.users.addRealmRoleMappings({ id: userId, roles: [role], }); } } // Remove old roles if (rolesToRemove && rolesToRemove.length > 0) { await kcAdminClient.users.delRealmRoleMappings({ id: userId, roles: rolesToRemove, }); } return NextResponse.json({ success: true }); } catch (error) { console.error("Error updating roles:", error); return NextResponse.json( { error: "Failed to update roles" }, { status: 500 } ); } }