carnet api

This commit is contained in:
alma 2025-04-20 15:52:38 +02:00
parent d0793dc45a
commit 3a48565b7d

View File

@ -13,8 +13,9 @@ declare global {
const prisma = global.prisma || new PrismaClient(); const prisma = global.prisma || new PrismaClient();
if (process.env.NODE_ENV !== 'production') global.prisma = prisma; if (process.env.NODE_ENV !== 'production') global.prisma = prisma;
// Cache for folder structure // Cache for folder structure and credentials
const folderCache = new Map<string, { folders: string[]; timestamp: number }>(); const folderCache = new Map<string, { folders: string[]; timestamp: number }>();
const credentialsCache = new Map<string, { password: string; timestamp: number }>();
async function sleep(ms: number) { async function sleep(ms: number) {
return new Promise(resolve => setTimeout(resolve, ms)); 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) { async function getWebDAVCredentials(nextcloudUrl: string, username: string, adminUsername: string, adminPassword: string, userId: string) {
try { try {
// Check if credentials exist in database // Check cache first
let credentials = await prisma.webDAVCredentials.findUnique({ const cachedCredentials = credentialsCache.get(userId);
where: { userId }, if (cachedCredentials) {
}); const cacheAge = Date.now() - cachedCredentials.timestamp;
if (cacheAge < 5 * 60 * 1000) { // 5 minutes cache
if (credentials) { return cachedCredentials.password;
// 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: '<?xml version="1.0" encoding="UTF-8"?><d:propfind xmlns:d="DAV:"><d:prop><d:resourcetype/></d:prop></d:propfind>',
});
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;
} }
// 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)}`, { const userInfoResponse = await fetch(`${nextcloudUrl}/ocs/v1.php/cloud/users/${encodeURIComponent(username)}`, {
headers: { headers: {
'Authorization': `Basic ${Buffer.from(`${adminUsername}:${adminPassword}`).toString('base64')}`, '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) { if (!userInfoResponse.ok) {
throw new Error(`Failed to get user info: ${userInfoResponse.status} ${userInfoResponse.statusText}`); 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}`); throw new Error(`Failed to set password: ${setPasswordResponse.status} ${setPasswordResponse.statusText}`);
} }
// Store the new credentials // Update cache
credentials = await prisma.webDAVCredentials.create({ credentialsCache.set(userId, {
data: { password: newPassword,
userId, timestamp: Date.now()
username,
password: newPassword,
},
}); });
// Try to create folders, but don't fail if it doesn't work // 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}`; const nextcloudUsername = `cube-${session.user.id}`;
console.log('Using Nextcloud username:', nextcloudUsername); 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 // Get or create WebDAV credentials
const webdavPassword = await getWebDAVCredentials( const webdavPassword = await getWebDAVCredentials(
nextcloudUrl, nextcloudUrl,