364 lines
12 KiB
TypeScript
364 lines
12 KiB
TypeScript
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';
|
|
import { PrismaClient } from '@prisma/client';
|
|
|
|
// Use a single PrismaClient instance
|
|
declare global {
|
|
var prisma: PrismaClient | undefined;
|
|
}
|
|
|
|
const prisma = global.prisma || new PrismaClient();
|
|
if (process.env.NODE_ENV !== 'production') global.prisma = prisma;
|
|
|
|
// Cache for folder structure and credentials
|
|
const folderCache = new Map<string, { folders: string[]; timestamp: number }>();
|
|
const credentialsCache = new Map<string, { password: string; timestamp: number }>();
|
|
|
|
// Cache for Nextcloud connectivity check
|
|
let lastConnectivityCheck = 0;
|
|
let isNextcloudAccessible = false;
|
|
|
|
async function sleep(ms: number) {
|
|
return new Promise(resolve => setTimeout(resolve, ms));
|
|
}
|
|
|
|
async function checkNextcloudConnectivity(nextcloudUrl: string): Promise<boolean> {
|
|
const now = Date.now();
|
|
if (now - lastConnectivityCheck < 5 * 60 * 1000) { // 5 minutes cache
|
|
return isNextcloudAccessible;
|
|
}
|
|
|
|
try {
|
|
const testResponse = await fetch(`${nextcloudUrl}/status.php`);
|
|
isNextcloudAccessible = testResponse.ok;
|
|
lastConnectivityCheck = now;
|
|
return isNextcloudAccessible;
|
|
} catch (error) {
|
|
console.error('Nextcloud connectivity check failed:', error);
|
|
isNextcloudAccessible = false;
|
|
lastConnectivityCheck = now;
|
|
return false;
|
|
}
|
|
}
|
|
|
|
async function parseXMLResponse(response: Response): Promise<any> {
|
|
const text = await response.text();
|
|
const parser = new DOMParser();
|
|
const xmlDoc = parser.parseFromString(text, 'text/xml');
|
|
|
|
// Check for parsing errors
|
|
const parserError = xmlDoc.getElementsByTagName('parsererror');
|
|
if (parserError.length > 0) {
|
|
console.error('XML Parsing Error:', parserError[0].textContent);
|
|
throw new Error('Failed to parse XML response');
|
|
}
|
|
|
|
const result: any = {};
|
|
const root = xmlDoc.documentElement;
|
|
|
|
if (root && root.nodeName === 'ocs') {
|
|
const data = root.getElementsByTagName('data')[0];
|
|
if (data) {
|
|
const children = data.childNodes;
|
|
for (let i = 0; i < children.length; i++) {
|
|
const child = children[i];
|
|
if (child.nodeType === 1) { // Element node
|
|
result[child.nodeName] = child.textContent;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
async function createFolder(nextcloudUrl: string, username: string, password: string, folderPath: string) {
|
|
try {
|
|
// First check if folder exists
|
|
const checkResponse = await fetch(`${nextcloudUrl}/remote.php/dav/files/${encodeURIComponent(username)}/${folderPath}`, {
|
|
method: 'PROPFIND',
|
|
headers: {
|
|
'Authorization': `Basic ${Buffer.from(`${username}:${password}`).toString('base64')}`,
|
|
'Depth': '0',
|
|
},
|
|
});
|
|
|
|
if (checkResponse.ok) {
|
|
console.log(`Folder ${folderPath} already exists`);
|
|
return;
|
|
}
|
|
|
|
// If folder doesn't exist, create it
|
|
const response = await fetch(`${nextcloudUrl}/remote.php/dav/files/${encodeURIComponent(username)}/${folderPath}`, {
|
|
method: 'MKCOL',
|
|
headers: {
|
|
'Authorization': `Basic ${Buffer.from(`${username}:${password}`).toString('base64')}`,
|
|
},
|
|
});
|
|
|
|
if (!response.ok && response.status !== 405) { // 405 means folder already exists
|
|
const errorText = await response.text();
|
|
console.error(`Failed to create folder ${folderPath}:`, {
|
|
status: response.status,
|
|
statusText: response.statusText,
|
|
error: errorText,
|
|
url: `${nextcloudUrl}/remote.php/dav/files/${encodeURIComponent(username)}/${folderPath}`
|
|
});
|
|
throw new Error(`Failed to create folder ${folderPath}: ${response.status} ${response.statusText}`);
|
|
}
|
|
} catch (error) {
|
|
console.error(`Error creating folder ${folderPath}:`, error);
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
async function ensureFolderStructure(nextcloudUrl: string, username: string, password: string) {
|
|
try {
|
|
// First, ensure the Private folder exists
|
|
await createFolder(nextcloudUrl, username, password, 'Private');
|
|
|
|
// Create all required subfolders
|
|
const subfolders = [
|
|
'Private/Diary',
|
|
'Private/Health',
|
|
'Private/Contacts',
|
|
'Private/Notes'
|
|
];
|
|
|
|
for (const folder of subfolders) {
|
|
await createFolder(nextcloudUrl, username, password, folder);
|
|
}
|
|
} catch (error) {
|
|
console.error('Error creating folder structure:', error);
|
|
// Don't throw the error, just log it
|
|
// This way we don't trigger password regeneration
|
|
}
|
|
}
|
|
|
|
async function getWebDAVCredentials(nextcloudUrl: string, username: string, adminUsername: string, adminPassword: string, userId: string) {
|
|
try {
|
|
// Check cache first
|
|
const cachedCredentials = credentialsCache.get(userId);
|
|
if (cachedCredentials) {
|
|
const cacheAge = Date.now() - cachedCredentials.timestamp;
|
|
if (cacheAge < 5 * 60 * 1000) { // 5 minutes cache
|
|
// Verify the cached credentials still work
|
|
const verifyResponse = await fetch(`${nextcloudUrl}/remote.php/dav/files/${encodeURIComponent(username)}/`, {
|
|
method: 'PROPFIND',
|
|
headers: {
|
|
'Authorization': `Basic ${Buffer.from(`${username}:${cachedCredentials.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) {
|
|
console.log('Using cached credentials');
|
|
return cachedCredentials.password;
|
|
}
|
|
|
|
// If verification failed, remove from cache
|
|
console.log('Cached credentials verification failed');
|
|
credentialsCache.delete(userId);
|
|
}
|
|
}
|
|
|
|
// 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')}`,
|
|
'OCS-APIRequest': 'true',
|
|
},
|
|
});
|
|
|
|
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}`);
|
|
}
|
|
|
|
// Try to use the admin password first
|
|
const adminVerifyResponse = await fetch(`${nextcloudUrl}/remote.php/dav/files/${encodeURIComponent(username)}/`, {
|
|
method: 'PROPFIND',
|
|
headers: {
|
|
'Authorization': `Basic ${Buffer.from(`${username}:${adminPassword}`).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 (adminVerifyResponse.ok) {
|
|
console.log('Using admin password for WebDAV access');
|
|
return adminPassword;
|
|
}
|
|
|
|
// If admin password doesn't work, generate a new password
|
|
const newPassword = Math.random().toString(36).slice(-12);
|
|
console.log('Setting new password for user');
|
|
|
|
// Set the user's password
|
|
const setPasswordResponse = 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: 'password',
|
|
value: newPassword,
|
|
}).toString(),
|
|
});
|
|
|
|
if (!setPasswordResponse.ok) {
|
|
throw new Error(`Failed to set password: ${setPasswordResponse.status} ${setPasswordResponse.statusText}`);
|
|
}
|
|
|
|
// Update cache
|
|
credentialsCache.set(userId, {
|
|
password: newPassword,
|
|
timestamp: Date.now()
|
|
});
|
|
|
|
// Try to create folders, but don't fail if it doesn't work
|
|
await ensureFolderStructure(nextcloudUrl, username, newPassword);
|
|
|
|
return newPassword;
|
|
} catch (error) {
|
|
console.error('Error in getWebDAVCredentials:', error);
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
async function getFolderStructure(nextcloudUrl: string, username: string, password: string): Promise<string[]> {
|
|
try {
|
|
const webdavUrl = `${nextcloudUrl}/remote.php/dav/files/${encodeURIComponent(username)}/Private/`;
|
|
const foldersResponse = await fetch(webdavUrl, {
|
|
method: 'PROPFIND',
|
|
headers: {
|
|
'Authorization': `Basic ${Buffer.from(`${username}:${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:displayname/></d:prop></d:propfind>',
|
|
});
|
|
|
|
if (foldersResponse.status === 429) {
|
|
// Rate limited, wait and retry
|
|
const retryAfter = foldersResponse.headers.get('Retry-After');
|
|
await sleep((retryAfter ? parseInt(retryAfter) : 5) * 1000);
|
|
return getFolderStructure(nextcloudUrl, username, password);
|
|
}
|
|
|
|
if (!foldersResponse.ok) {
|
|
throw new Error(`Failed to fetch folders: ${foldersResponse.status} ${foldersResponse.statusText}`);
|
|
}
|
|
|
|
const folderData = await foldersResponse.text();
|
|
const parser = new DOMParser();
|
|
const xmlDoc = parser.parseFromString(folderData, 'text/xml');
|
|
const responses = Array.from(xmlDoc.getElementsByTagName('d:response'));
|
|
|
|
const folders: string[] = [];
|
|
for (const response of responses) {
|
|
const resourceType = response.getElementsByTagName('d:resourcetype')[0];
|
|
const isCollection = resourceType?.getElementsByTagName('d:collection').length > 0;
|
|
|
|
if (isCollection) {
|
|
const href = response.getElementsByTagName('d:href')[0]?.textContent;
|
|
if (href) {
|
|
const folderName = href.split('/').pop();
|
|
if (folderName && folderName !== 'Private') {
|
|
folders.push(folderName);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
return folders;
|
|
} catch (error) {
|
|
console.error('Error getting folder structure:', error);
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
export async function GET() {
|
|
try {
|
|
const session = await getServerSession(authOptions);
|
|
if (!session?.user?.email || !session?.user?.id || !session?.accessToken) {
|
|
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) {
|
|
console.error('Missing Nextcloud configuration');
|
|
return NextResponse.json({ error: 'Nextcloud configuration is missing' }, { status: 500 });
|
|
}
|
|
|
|
// Check Nextcloud connectivity with caching
|
|
const isAccessible = await checkNextcloudConnectivity(nextcloudUrl);
|
|
if (!isAccessible) {
|
|
return NextResponse.json({ error: "Nextcloud n'est pas accessible" }, { status: 503 });
|
|
}
|
|
|
|
// Use the Keycloak ID as the Nextcloud username
|
|
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,
|
|
nextcloudUsername,
|
|
adminUsername,
|
|
adminPassword,
|
|
session.user.id
|
|
);
|
|
|
|
if (!webdavPassword) {
|
|
throw new Error('Failed to get WebDAV credentials');
|
|
}
|
|
|
|
// Get folder structure
|
|
const folders = await getFolderStructure(nextcloudUrl, nextcloudUsername, webdavPassword);
|
|
|
|
// Update cache
|
|
folderCache.set(nextcloudUsername, {
|
|
folders,
|
|
timestamp: Date.now()
|
|
});
|
|
|
|
return NextResponse.json({
|
|
isConnected: true,
|
|
folders
|
|
});
|
|
} catch (error) {
|
|
console.error('Error in Nextcloud status endpoint:', error);
|
|
return NextResponse.json(
|
|
{ error: error instanceof Error ? error.message : 'An error occurred' },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
} |