Neah/app/api/nextcloud/init/route.ts
2025-04-21 11:28:55 +02:00

60 lines
2.0 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 { Buffer } from 'buffer';
export async function POST() {
try {
const session = await getServerSession(authOptions);
if (!session?.user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const nextcloudUrl = process.env.NEXTCLOUD_URL;
const adminUsername = process.env.NEXTCLOUD_ADMIN_USERNAME;
const adminPassword = process.env.NEXTCLOUD_ADMIN_PASSWORD;
if (!nextcloudUrl || !adminUsername || !adminPassword) {
return NextResponse.json({ error: 'Nextcloud configuration missing' }, { status: 500 });
}
const username = `cube-${session.user.id}`;
const userId = session.user.id;
// Get or create WebDAV credentials
const password = await getWebDAVCredentials(nextcloudUrl, username, adminUsername, adminPassword, userId);
// Ensure folder structure exists
await ensureFolderStructure(nextcloudUrl, username, password);
// Store initialization state in session
const updatedSession = {
...session,
user: {
...session.user,
nextcloudInitialized: true
}
};
return NextResponse.json({
success: true,
message: 'Nextcloud initialized successfully'
});
} catch (error) {
console.error('Nextcloud initialization failed:', error);
return NextResponse.json({
error: 'Failed to initialize Nextcloud',
details: error instanceof Error ? error.message : 'Unknown error'
}, { status: 500 });
}
}
// Helper functions from status/route.ts
async function getWebDAVCredentials(nextcloudUrl: string, username: string, adminUsername: string, adminPassword: string, userId: string) {
// ... existing getWebDAVCredentials implementation ...
}
async function ensureFolderStructure(nextcloudUrl: string, username: string, password: string) {
// ... existing ensureFolderStructure implementation ...
}