77 lines
2.2 KiB
TypeScript
77 lines
2.2 KiB
TypeScript
import { getServerSession } from "next-auth";
|
|
import { authOptions } from "../../auth/[...nextauth]/route";
|
|
import { NextResponse } from "next/server";
|
|
|
|
//TODO: Ajouter la suppression automatique du compte Nextcloud
|
|
export async function DELETE(
|
|
req: Request,
|
|
{ params }: { params: { id: string } }
|
|
) {
|
|
const session = await getServerSession(authOptions);
|
|
|
|
if (!session) {
|
|
return NextResponse.json({ error: "Non autorisé" }, { status: 401 });
|
|
}
|
|
|
|
try {
|
|
// First get an admin token using client credentials
|
|
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 tokenData = await tokenResponse.json();
|
|
|
|
if (!tokenResponse.ok) {
|
|
console.error("Failed to get admin token:", tokenData);
|
|
return NextResponse.json(
|
|
{ error: "Erreur d'authentification" },
|
|
{ status: 401 }
|
|
);
|
|
}
|
|
|
|
// Delete user using admin token
|
|
const response = await fetch(
|
|
`${process.env.KEYCLOAK_BASE_URL}/admin/realms/${process.env.KEYCLOAK_REALM}/users/${params.id}`,
|
|
{
|
|
method: "DELETE",
|
|
headers: {
|
|
Authorization: `Bearer ${tokenData.access_token}`,
|
|
},
|
|
}
|
|
);
|
|
|
|
console.log("Delete response:", {
|
|
status: response.status,
|
|
ok: response.ok
|
|
});
|
|
|
|
if (!response.ok) {
|
|
const errorText = await response.text();
|
|
console.error("Delete error:", errorText);
|
|
return NextResponse.json(
|
|
{ error: "Erreur lors de la suppression", details: errorText },
|
|
{ status: response.status }
|
|
);
|
|
}
|
|
|
|
return NextResponse.json({ success: true });
|
|
} catch (error) {
|
|
console.error("Error deleting user:", error);
|
|
return NextResponse.json(
|
|
{ error: "Erreur serveur", details: error },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
}
|