carnet api
This commit is contained in:
parent
d0793dc45a
commit
3a48565b7d
@ -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<string, { folders: string[]; timestamp: number }>();
|
||||
const credentialsCache = new Map<string, { password: string; timestamp: number }>();
|
||||
|
||||
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: '<?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;
|
||||
// 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,
|
||||
|
||||
Loading…
Reference in New Issue
Block a user