carnet api

This commit is contained in:
alma 2025-04-20 14:18:40 +02:00
parent cb818d1ab7
commit 05257e3d7e

View File

@ -2,11 +2,69 @@ import { NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/app/api/auth/[...nextauth]/route';
import { DOMParser } from '@xmldom/xmldom';
import { Buffer } from 'buffer';
async function sleep(ms: number) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function getWebDAVCredentials(nextcloudUrl: string, username: string, adminUsername: string, adminPassword: string) {
// First, try to get the user's WebDAV password
const userInfoResponse = await fetch(`${nextcloudUrl}/ocs/v1.php/cloud/users/${encodeURIComponent(username)}`, {
headers: {
'Authorization': `Basic ${Buffer.from(`${adminUsername}:${adminPassword}`).toString('base64')}`,
'OCS-APIRequest': 'true',
},
});
if (!userInfoResponse.ok) {
console.error('Failed to get user info:', await userInfoResponse.text());
return null;
}
const userInfo = await userInfoResponse.json();
const webdavPassword = userInfo.ocs.data?.webdav_password;
if (!webdavPassword) {
// If no WebDAV password exists, create one
const createPasswordResponse = await fetch(`${nextcloudUrl}/ocs/v1.php/cloud/users/${encodeURIComponent(username)}`, {
method: 'PUT',
headers: {
'Authorization': `Basic ${Buffer.from(`${adminUsername}:${adminPassword}`).toString('base64')}`,
'OCS-APIRequest': 'true',
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({
key: 'webdav_password',
value: Math.random().toString(36).slice(-8), // Generate a random password
}).toString(),
});
if (!createPasswordResponse.ok) {
console.error('Failed to create WebDAV password:', await createPasswordResponse.text());
return null;
}
// Get the new WebDAV password
const newUserInfoResponse = await fetch(`${nextcloudUrl}/ocs/v1.php/cloud/users/${encodeURIComponent(username)}`, {
headers: {
'Authorization': `Basic ${Buffer.from(`${adminUsername}:${adminPassword}`).toString('base64')}`,
'OCS-APIRequest': 'true',
},
});
if (!newUserInfoResponse.ok) {
console.error('Failed to get new user info:', await newUserInfoResponse.text());
return null;
}
const newUserInfo = await newUserInfoResponse.json();
return newUserInfo.ocs.data?.webdav_password;
}
return webdavPassword;
}
export async function GET() {
try {
const session = await getServerSession(authOptions);
@ -19,7 +77,10 @@ export async function GET() {
}
const nextcloudUrl = process.env.NEXTCLOUD_URL;
if (!nextcloudUrl) {
const adminUsername = process.env.NEXTCLOUD_ADMIN_USERNAME;
const adminPassword = process.env.NEXTCLOUD_ADMIN_PASSWORD;
if (!nextcloudUrl || !adminUsername || !adminPassword) {
console.error('Missing Nextcloud configuration');
return NextResponse.json(
{ error: 'Nextcloud configuration is missing' },
@ -38,16 +99,25 @@ export async function GET() {
}
try {
// Get user's folders using WebDAV with OIDC token
// Get or create WebDAV credentials
const webdavPassword = await getWebDAVCredentials(
nextcloudUrl,
session.user.email,
adminUsername,
adminPassword
);
if (!webdavPassword) {
throw new Error('Failed to get WebDAV credentials');
}
// Get user's folders using WebDAV with Basic authentication
const webdavUrl = `${nextcloudUrl}/remote.php/dav/files/${encodeURIComponent(session.user.email)}/`;
console.log('Requesting WebDAV URL:', webdavUrl);
const foldersResponse = await fetch(webdavUrl, {
headers: {
'Authorization': `Bearer ${session.accessToken}`,
'OIDC_CLAIM_sub': session.user.id, // Keycloak subject ID
'OIDC_CLAIM_email': session.user.email,
'OIDC_CLAIM_preferred_username': session.user.username,
'Authorization': `Basic ${Buffer.from(`${session.user.email}:${webdavPassword}`).toString('base64')}`,
'Depth': '1',
'Content-Type': 'application/xml',
},