186 lines
5.6 KiB
TypeScript
186 lines
5.6 KiB
TypeScript
import { getServerSession } from "next-auth/next";
|
|
import { authOptions } from "@/app/api/auth/options";
|
|
import { NextResponse } from "next/server";
|
|
import { prisma } from "@/lib/prisma";
|
|
|
|
async function getAdminToken() {
|
|
try {
|
|
const tokenResponse = await fetch(
|
|
`${process.env.KEYCLOAK_BASE_URL}/realms/${process.env.KEYCLOAK_REALM}/protocol/openid-connect/token`,
|
|
{
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/x-www-form-urlencoded',
|
|
},
|
|
body: new URLSearchParams({
|
|
grant_type: 'client_credentials',
|
|
client_id: process.env.KEYCLOAK_CLIENT_ID!,
|
|
client_secret: process.env.KEYCLOAK_CLIENT_SECRET!,
|
|
}),
|
|
}
|
|
);
|
|
|
|
const data = await tokenResponse.json();
|
|
if (!tokenResponse.ok || !data.access_token) {
|
|
console.error('Token Error:', data);
|
|
return null;
|
|
}
|
|
|
|
return data.access_token;
|
|
} catch (error) {
|
|
console.error('Token Error:', error);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
export async function GET(req: Request, props: { params: Promise<{ userId: string }> }) {
|
|
const params = await props.params;
|
|
const session = await getServerSession(authOptions);
|
|
|
|
if (!session) {
|
|
return NextResponse.json({ error: "Non autorisé" }, { status: 401 });
|
|
}
|
|
|
|
try {
|
|
const token = await getAdminToken();
|
|
if (!token) {
|
|
return NextResponse.json({ error: "Erreur d'authentification" }, { status: 401 });
|
|
}
|
|
|
|
// Get user groups
|
|
const groupsResponse = await fetch(
|
|
`${process.env.KEYCLOAK_BASE_URL}/admin/realms/${process.env.KEYCLOAK_REALM}/users/${params.userId}/groups`,
|
|
{
|
|
headers: {
|
|
'Authorization': `Bearer ${token}`,
|
|
},
|
|
}
|
|
);
|
|
|
|
if (!groupsResponse.ok) {
|
|
const errorData = await groupsResponse.json();
|
|
console.error("Failed to get user groups:", errorData);
|
|
return NextResponse.json({ error: "Failed to get user groups" }, { status: groupsResponse.status });
|
|
}
|
|
|
|
const groups = await groupsResponse.json();
|
|
|
|
// Enrich groups with calendar colors from database
|
|
const enrichedGroups = await Promise.all(
|
|
groups.map(async (group: any) => {
|
|
try {
|
|
const calendar = await prisma.calendar.findFirst({
|
|
where: {
|
|
name: `Groupe: ${group.name}`,
|
|
},
|
|
select: {
|
|
color: true,
|
|
},
|
|
});
|
|
|
|
return {
|
|
...group,
|
|
calendarColor: calendar?.color || null,
|
|
};
|
|
} catch (error) {
|
|
console.error(`Error fetching calendar color for group ${group.name}:`, error);
|
|
return {
|
|
...group,
|
|
calendarColor: null,
|
|
};
|
|
}
|
|
})
|
|
);
|
|
|
|
return NextResponse.json(enrichedGroups);
|
|
} catch (error) {
|
|
console.error("Error in get user groups:", error);
|
|
return NextResponse.json({ error: "Internal server error" }, { status: 500 });
|
|
}
|
|
}
|
|
|
|
export async function POST(req: Request, props: { params: Promise<{ userId: string }> }) {
|
|
const params = await props.params;
|
|
const session = await getServerSession(authOptions);
|
|
|
|
if (!session) {
|
|
return NextResponse.json({ error: "Non autorisé" }, { status: 401 });
|
|
}
|
|
|
|
try {
|
|
const { groupId } = await req.json();
|
|
|
|
const token = await getAdminToken();
|
|
if (!token) {
|
|
return NextResponse.json({ error: "Erreur d'authentification" }, { status: 401 });
|
|
}
|
|
|
|
// Add user to group
|
|
const addResponse = await fetch(
|
|
`${process.env.KEYCLOAK_BASE_URL}/admin/realms/${process.env.KEYCLOAK_REALM}/users/${params.userId}/groups/${groupId}`,
|
|
{
|
|
method: 'PUT',
|
|
headers: {
|
|
'Authorization': `Bearer ${token}`,
|
|
},
|
|
}
|
|
);
|
|
|
|
if (!addResponse.ok) {
|
|
const errorData = await addResponse.json();
|
|
console.error("Failed to add user to group:", errorData);
|
|
return NextResponse.json({ error: "Failed to add user to group" }, { status: addResponse.status });
|
|
}
|
|
|
|
return NextResponse.json({ success: true });
|
|
} catch (error) {
|
|
console.error("Error in add user to group:", error);
|
|
return NextResponse.json({ error: "Internal server error" }, { status: 500 });
|
|
}
|
|
}
|
|
|
|
export async function DELETE(req: Request, props: { params: Promise<{ userId: string }> }) {
|
|
const params = await props.params;
|
|
const session = await getServerSession(authOptions);
|
|
|
|
if (!session) {
|
|
return NextResponse.json({ error: "Non autorisé" }, { status: 401 });
|
|
}
|
|
|
|
try {
|
|
const { searchParams } = new URL(req.url);
|
|
const groupId = searchParams.get('groupId');
|
|
|
|
if (!groupId) {
|
|
return NextResponse.json({ error: "groupId is required" }, { status: 400 });
|
|
}
|
|
|
|
const token = await getAdminToken();
|
|
if (!token) {
|
|
return NextResponse.json({ error: "Erreur d'authentification" }, { status: 401 });
|
|
}
|
|
|
|
// Remove user from group
|
|
const removeResponse = await fetch(
|
|
`${process.env.KEYCLOAK_BASE_URL}/admin/realms/${process.env.KEYCLOAK_REALM}/users/${params.userId}/groups/${groupId}`,
|
|
{
|
|
method: 'DELETE',
|
|
headers: {
|
|
'Authorization': `Bearer ${token}`,
|
|
},
|
|
}
|
|
);
|
|
|
|
if (!removeResponse.ok) {
|
|
const errorData = await removeResponse.json();
|
|
console.error("Failed to remove user from group:", errorData);
|
|
return NextResponse.json({ error: "Failed to remove user from group" }, { status: removeResponse.status });
|
|
}
|
|
|
|
return NextResponse.json({ success: true });
|
|
} catch (error) {
|
|
console.error("Error in remove user from group:", error);
|
|
return NextResponse.json({ error: "Internal server error" }, { status: 500 });
|
|
}
|
|
}
|