NeahNew/app/api/missions/[missionId]/attachments/route.ts
2025-05-06 13:17:44 +02:00

78 lines
2.4 KiB
TypeScript

import { NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from "@/app/api/auth/options";
import { prisma } from '@/lib/prisma';
import { getPublicUrl, S3_CONFIG } from '@/lib/s3';
// 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 };
}
// GET endpoint to list all attachments for a mission
export async function GET(request: Request, props: { params: Promise<{ missionId: 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 } = params;
if (!missionId) {
return NextResponse.json({ error: 'Mission ID is 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 } } }
]
},
});
if (!mission) {
return NextResponse.json({ error: 'Mission not found or access denied' }, { status: 404 });
}
// Get all attachments for the mission
const attachments = await prisma.attachment.findMany({
where: { missionId },
orderBy: { createdAt: 'desc' },
select: {
id: true,
filename: true,
filePath: true,
fileType: true,
fileSize: true,
createdAt: true
}
});
// Add public URLs to attachments
const attachmentsWithUrls = attachments.map(attachment => ({
...attachment,
publicUrl: `/api/missions/image/${attachment.filePath}`
}));
return NextResponse.json(attachmentsWithUrls);
} catch (error) {
console.error('Error fetching mission attachments:', error);
return NextResponse.json({
error: 'Internal server error',
details: error instanceof Error ? error.message : String(error)
}, { status: 500 });
}
}