From 3a48565b7d51278042e54b3b69f6d938338fe7c7 Mon Sep 17 00:00:00 2001 From: alma Date: Sun, 20 Apr 2025 15:52:38 +0200 Subject: [PATCH] carnet api --- app/api/nextcloud/status/route.ts | 66 ++++++++++++++----------------- 1 file changed, 30 insertions(+), 36 deletions(-) diff --git a/app/api/nextcloud/status/route.ts b/app/api/nextcloud/status/route.ts index f06a0c04..4a3b2aa4 100644 --- a/app/api/nextcloud/status/route.ts +++ b/app/api/nextcloud/status/route.ts @@ -13,8 +13,9 @@ declare global { const prisma = global.prisma || new PrismaClient(); if (process.env.NODE_ENV !== 'production') global.prisma = prisma; -// Cache for folder structure +// Cache for folder structure and credentials const folderCache = new Map(); +const credentialsCache = new Map(); async function sleep(ms: number) { return new Promise(resolve => setTimeout(resolve, ms)); @@ -118,37 +119,16 @@ async function ensureFolderStructure(nextcloudUrl: string, username: string, pas async function getWebDAVCredentials(nextcloudUrl: string, username: string, adminUsername: string, adminPassword: string, userId: string) { try { - // Check if credentials exist in database - let credentials = await prisma.webDAVCredentials.findUnique({ - where: { userId }, - }); - - if (credentials) { - // Verify existing credentials still work - const verifyResponse = await fetch(`${nextcloudUrl}/remote.php/dav/files/${encodeURIComponent(username)}/`, { - method: 'PROPFIND', - headers: { - 'Authorization': `Basic ${Buffer.from(`${username}:${credentials.password}`).toString('base64')}`, - 'Depth': '1', - 'Content-Type': 'application/xml', - }, - body: '', - }); - - if (verifyResponse.ok) { - // Try to create folders, but don't fail if it doesn't work - await ensureFolderStructure(nextcloudUrl, username, credentials.password); - return credentials.password; + // Check cache first + const cachedCredentials = credentialsCache.get(userId); + if (cachedCredentials) { + const cacheAge = Date.now() - cachedCredentials.timestamp; + if (cacheAge < 5 * 60 * 1000) { // 5 minutes cache + return cachedCredentials.password; } - - // Only delete credentials if verification actually failed - console.log('Credentials verification failed, deleting old credentials'); - await prisma.webDAVCredentials.delete({ - where: { userId }, - }); } - // Get user info from Nextcloud + // First check if user exists in Nextcloud const userInfoResponse = await fetch(`${nextcloudUrl}/ocs/v1.php/cloud/users/${encodeURIComponent(username)}`, { headers: { 'Authorization': `Basic ${Buffer.from(`${adminUsername}:${adminPassword}`).toString('base64')}`, @@ -156,6 +136,11 @@ async function getWebDAVCredentials(nextcloudUrl: string, username: string, admi }, }); + if (userInfoResponse.status === 404) { + console.log(`User ${username} does not exist in Nextcloud`); + throw new Error(`User ${username} does not exist in Nextcloud`); + } + if (!userInfoResponse.ok) { throw new Error(`Failed to get user info: ${userInfoResponse.status} ${userInfoResponse.statusText}`); } @@ -182,13 +167,10 @@ async function getWebDAVCredentials(nextcloudUrl: string, username: string, admi throw new Error(`Failed to set password: ${setPasswordResponse.status} ${setPasswordResponse.statusText}`); } - // Store the new credentials - credentials = await prisma.webDAVCredentials.create({ - data: { - userId, - username, - password: newPassword, - }, + // Update cache + credentialsCache.set(userId, { + password: newPassword, + timestamp: Date.now() }); // Try to create folders, but don't fail if it doesn't work @@ -229,6 +211,18 @@ export async function GET() { const nextcloudUsername = `cube-${session.user.id}`; console.log('Using Nextcloud username:', nextcloudUsername); + // Check cache first + const cachedData = folderCache.get(nextcloudUsername); + if (cachedData) { + const cacheAge = Date.now() - cachedData.timestamp; + if (cacheAge < 5 * 60 * 1000) { // 5 minutes cache + return NextResponse.json({ + isConnected: true, + folders: cachedData.folders + }); + } + } + // Get or create WebDAV credentials const webdavPassword = await getWebDAVCredentials( nextcloudUrl,