NeahNew/app/api/missions/[missionId]/attachments/[attachmentId]/route.ts
2025-05-05 12:55:09 +02:00

81 lines
2.5 KiB
TypeScript

import { NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/app/api/auth/[...nextauth]/route';
import { prisma } from '@/lib/prisma';
import { deleteMissionAttachment } from '@/lib/mission-uploads';
// Helper function to check authentication
async function checkAuth(request: Request) {
const session = await getServerSession(authOptions);
if (!session?.user?.id) {
console.error('Unauthorized access attempt:', {
url: request.url,
method: request.method,
headers: Object.fromEntries(request.headers)
});
return { authorized: false, userId: null };
}
return { authorized: true, userId: session.user.id };
}
// DELETE endpoint to remove an attachment
export async function DELETE(
request: Request,
props: { params: Promise<{ missionId: string, attachmentId: string }> }
) {
const params = await props.params;
try {
const { authorized, userId } = await checkAuth(request);
if (!authorized || !userId) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const { missionId, attachmentId } = params;
if (!missionId || !attachmentId) {
return NextResponse.json({ error: 'Mission ID and Attachment ID are required' }, { status: 400 });
}
// Check if mission exists and user has access to it
const mission = await prisma.mission.findFirst({
where: {
id: missionId,
OR: [
{ creatorId: userId },
{ missionUsers: { some: { userId, role: 'gardien-memoire' } } } // Only mission creator or memory guardian can delete
]
},
});
if (!mission) {
return NextResponse.json({ error: 'Mission not found or access denied' }, { status: 404 });
}
// Get the attachment to delete
const attachment = await prisma.attachment.findUnique({
where: {
id: attachmentId,
missionId
}
});
if (!attachment) {
return NextResponse.json({ error: 'Attachment not found' }, { status: 404 });
}
// Delete the file from Minio
await deleteMissionAttachment(attachment.filePath);
// Delete the attachment record from the database
await prisma.attachment.delete({
where: { id: attachmentId }
});
return NextResponse.json({ success: true });
} catch (error) {
console.error('Error deleting attachment:', error);
return NextResponse.json({
error: 'Internal server error',
details: error instanceof Error ? error.message : String(error)
}, { status: 500 });
}
}