73 lines
2.1 KiB
TypeScript
73 lines
2.1 KiB
TypeScript
import { NextRequest, NextResponse } from "next/server";
|
||
import { authenticateAPIRequest } from "@/app/lib/api-auth";
|
||
import { hasPermission, PERMISSIONS } from "@/app/lib/permissions";
|
||
import { db } from "@/db";
|
||
import { user, images, apiKeys } from "@/db/schema";
|
||
import { eq } from "drizzle-orm";
|
||
|
||
/**
|
||
* DELETE /api/v1/admin/users/[id]
|
||
* Kullanıcıyı sil (Sadece admin)
|
||
* Kullanıcının tüm resimleri ve API anahtarları da silinir
|
||
*/
|
||
export async function DELETE(
|
||
request: NextRequest,
|
||
{ params }: { params: Promise<{ id: string }> }
|
||
) {
|
||
const auth = await authenticateAPIRequest(request);
|
||
|
||
if (!auth.authenticated) {
|
||
return NextResponse.json({ error: auth.error }, { status: 401 });
|
||
}
|
||
|
||
// Permission kontrolü
|
||
if (!hasPermission(auth.role!, PERMISSIONS.USER_DELETE)) {
|
||
return NextResponse.json(
|
||
{ error: "Bu işlem için yetkiniz yok. Sadece adminler kullanıcı silebilir." },
|
||
{ status: 403 }
|
||
);
|
||
}
|
||
|
||
try {
|
||
const { id: userId } = await params;
|
||
|
||
// Kendi hesabını silmeyi engelle
|
||
if (userId === auth.userId) {
|
||
return NextResponse.json(
|
||
{ error: "Kendi hesabınızı silemezsiniz" },
|
||
{ status: 400 }
|
||
);
|
||
}
|
||
|
||
// Kullanıcının var olup olmadığını kontrol et
|
||
const targetUser = await db.select().from(user).where(eq(user.id, userId)).limit(1);
|
||
if (targetUser.length === 0) {
|
||
return NextResponse.json({ error: "Kullanıcı bulunamadı" }, { status: 404 });
|
||
}
|
||
|
||
// Kullanıcının resimlerini sil
|
||
const deletedImages = await db.delete(images).where(eq(images.userId, userId));
|
||
|
||
// Kullanıcının API anahtarlarını sil
|
||
await db.delete(apiKeys).where(eq(apiKeys.userId, userId));
|
||
|
||
// Kullanıcıyı sil
|
||
await db.delete(user).where(eq(user.id, userId));
|
||
|
||
return NextResponse.json({
|
||
success: true,
|
||
message: "Kullanıcı başarıyla silindi",
|
||
data: {
|
||
deletedUserId: userId,
|
||
deletedUser: targetUser[0].email,
|
||
},
|
||
});
|
||
} catch (error: any) {
|
||
console.error("Kullanıcı silme hatası:", error);
|
||
return NextResponse.json(
|
||
{ error: "Kullanıcı silinemedi" },
|
||
{ status: 500 }
|
||
);
|
||
}
|
||
}
|