NeahNew/app/api/storage/files/route.ts
2025-05-05 13:04:01 +02:00

163 lines
6.0 KiB
TypeScript

import { NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from "@/app/api/auth/options";
import { listUserObjects, putObject, deleteObject } 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 files in a folder
export async function GET(request: Request) {
try {
const { authorized, userId } = await checkAuth(request);
if (!authorized || !userId) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const { searchParams } = new URL(request.url);
const folderParam = searchParams.get('folder');
if (!folderParam) {
return NextResponse.json({ error: 'Folder parameter is required' }, { status: 400 });
}
// Try both lowercase and original case to maintain compatibility
// MinIO/S3 is case-sensitive, so we need to handle both formats
const normalizedFolder = folderParam.toLowerCase();
console.log(`Listing files for user ${userId} in folder: ${folderParam} (normalized: ${normalizedFolder})`);
// First try with the exact folder name as provided
let files = await listUserObjects(userId, folderParam);
// If no files found with original case, try with lowercase
if (files.length === 0 && folderParam !== normalizedFolder) {
console.log(`No files found with original case, trying lowercase: ${normalizedFolder}`);
files = await listUserObjects(userId, normalizedFolder);
}
return NextResponse.json(files);
} catch (error) {
console.error('Error listing files:', error);
return NextResponse.json({ error: 'Internal server error', details: error instanceof Error ? error.message : String(error) }, { status: 500 });
}
}
// POST endpoint to create a new file
export async function POST(request: Request) {
try {
const { authorized, userId } = await checkAuth(request);
if (!authorized || !userId) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const body = await request.json().catch(() => ({}));
const { title, content, folder } = body;
if (!title || !content || !folder) {
return NextResponse.json({ error: 'Missing required fields', received: { title: !!title, content: !!content, folder: !!folder } }, { status: 400 });
}
// Normalize folder name
const normalizedFolder = folder.toLowerCase();
// Create the full key (path) for the S3 object
// Remove 'pages/' prefix since it's already the bucket name
const key = `user-${userId}/${normalizedFolder}/${title}${title.endsWith('.md') ? '' : '.md'}`;
console.log('Creating file in S3:', { key, contentLength: content.length });
// Save the file to S3
const file = await putObject(key, content);
return NextResponse.json(file);
} catch (error) {
console.error('Error creating file:', error);
return NextResponse.json({ error: 'Internal server error', details: error instanceof Error ? error.message : String(error) }, { status: 500 });
}
}
// PUT endpoint to update an existing file
export async function PUT(request: Request) {
try {
const { authorized, userId } = await checkAuth(request);
if (!authorized || !userId) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const body = await request.json().catch(() => ({}));
const { id, title, content, folder, mime } = body;
// Check if this is using the direct id (key) or needs to construct one
let key: string;
if (id) {
// Ensure the user can only access their own files
if (!id.includes(`user-${userId}/`)) {
return NextResponse.json({ error: 'Unauthorized access to file' }, { status: 403 });
}
key = id;
} else {
// If id is not provided, construct it from folder and title
if (!title || !folder) {
return NextResponse.json({ error: 'Missing required fields', received: { title: !!title, folder: !!folder } }, { status: 400 });
}
const normalizedFolder = folder.toLowerCase();
// Remove 'pages/' prefix since it's already the bucket name
key = `user-${userId}/${normalizedFolder}/${title}${title.endsWith('.md') ? '' : '.md'}`;
}
console.log('Updating file in S3:', { key, contentLength: content?.length });
// Update the file
const file = await putObject(key, content, mime);
return NextResponse.json(file);
} catch (error) {
console.error('Error updating file:', error);
return NextResponse.json({ error: 'Internal server error', details: error instanceof Error ? error.message : String(error) }, { status: 500 });
}
}
// DELETE endpoint to delete a file
export async function DELETE(request: Request) {
try {
const { authorized, userId } = await checkAuth(request);
if (!authorized || !userId) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const { searchParams } = new URL(request.url);
const id = searchParams.get('id');
if (!id) {
return NextResponse.json({ error: 'Missing file id' }, { status: 400 });
}
// Ensure the user can only delete their own files
if (!id.includes(`user-${userId}/`)) {
return NextResponse.json({ error: 'Unauthorized access to file' }, { status: 403 });
}
console.log('Deleting file from S3:', { key: id });
// Delete the file
await deleteObject(id);
return NextResponse.json({ success: true });
} catch (error) {
console.error('Error deleting file:', error);
return NextResponse.json({ error: 'Internal server error', details: error instanceof Error ? error.message : String(error) }, { status: 500 });
}
}