Neah/app/api/nextcloud/files/content/route.ts
2025-04-21 11:31:39 +02:00

94 lines
2.9 KiB
TypeScript

import { NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { PrismaClient } from '@prisma/client';
import { authOptions } from '@/app/api/auth/[...nextauth]/route';
import { createClient } from 'webdav';
// Use a single PrismaClient instance
declare global {
var prisma: PrismaClient | undefined;
}
const prisma = global.prisma || new PrismaClient();
if (process.env.NODE_ENV !== 'production') global.prisma = prisma;
// Helper function to create WebDAV client
const createWebDAVClient = async (userId: string) => {
const credentials = await prisma.webDAVCredentials.findUnique({
where: { userId },
});
if (!credentials) {
throw new Error('No WebDAV credentials found');
}
const baseURL = process.env.NEXTCLOUD_URL;
if (!baseURL) {
throw new Error('NEXTCLOUD_URL environment variable is not set');
}
const normalizedBaseURL = baseURL.endsWith('/') ? baseURL.slice(0, -1) : baseURL;
const webdavURL = `${normalizedBaseURL}/remote.php/dav`;
return {
client: createClient(webdavURL, {
username: credentials.username,
password: credentials.password,
authType: 'password',
}),
username: credentials.username
};
};
export async function GET(request: Request) {
try {
const { searchParams } = new URL(request.url);
const path = searchParams.get('path');
if (!path) {
return NextResponse.json({ error: 'Path parameter is required' }, { status: 400 });
}
const session = await getServerSession(authOptions);
if (!session?.user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const nextcloudUrl = process.env.NEXTCLOUD_URL;
const username = `cube-${session.user.id}`;
// Get credentials without logging
const credentials = await prisma.webDAVCredentials.findUnique({
where: { userId: session.user.id }
});
if (!credentials) {
return NextResponse.json({ error: 'Nextcloud credentials not found' }, { status: 404 });
}
// Make request without logging sensitive information
const response = await fetch(`${nextcloudUrl}/remote.php/dav${path}`, {
method: 'GET',
headers: {
'Authorization': `Basic ${Buffer.from(`${username}:${credentials.password}`).toString('base64')}`,
},
});
if (!response.ok) {
return NextResponse.json({ error: 'Failed to fetch file content' }, { status: response.status });
}
const content = await response.text();
// For VCF files, don't log the content
if (path.endsWith('.vcf')) {
return NextResponse.json({ content });
}
return NextResponse.json({ content });
} catch (error) {
// Log error without sensitive information
console.error('Error fetching file content:', error instanceof Error ? error.message : 'Unknown error');
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}