Files
image-apiv2/app/api/v1/images/[id]/route.ts
Beyhan Oğur 71eff2d979 first commit
2026-04-26 22:09:32 +03:00

81 lines
2.1 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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 { images } from "@/db/schema";
import { eq, and } from "drizzle-orm";
import { unlink } from "fs/promises";
/**
* DELETE /api/v1/images/[id]
* Resim sil
* Kullanıcılar sadece kendi resimlerini silebilir
* Moderator ve adminler herhangi bir resmi silebilir
*
* Headers:
* - Authorization: Bearer <jwt_token>
*/
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 });
}
try {
const { id } = await params;
// Permission kontrolü - moderator ve admin herhangi bir resmi silebilir
const canDeleteAny = hasPermission(auth.role!, PERMISSIONS.IMAGE_DELETE_ANY);
// Resmi bul
const imageRecords = await db
.select()
.from(images)
.where(eq(images.id, id))
.limit(1);
if (imageRecords.length === 0) {
return NextResponse.json(
{ error: "Resim bulunamadı" },
{ status: 404 }
);
}
const image = imageRecords[0];
// Yetki kontrolü - kendi resmi değilse ve delete any yetkisi yoksa reddedilir
if (!canDeleteAny && image.userId !== auth.userId) {
return NextResponse.json(
{ error: "Bu resmi silme yetkiniz yok" },
{ status: 403 }
);
}
// Dosyayı sil
try {
await unlink(image.filePath);
} catch (fileError) {
console.error("Dosya silinemedi:", fileError);
// Devam et, veritabanından sil
}
// Veritabanından sil
await db.delete(images).where(eq(images.id, id));
return NextResponse.json({
success: true,
message: "Resim başarıyla silindi",
});
} catch (error: any) {
console.error("API - Resim silme hatası:", error);
return NextResponse.json(
{ error: "Resim silinemedi" },
{ status: 500 }
);
}
}