This commit is contained in:
alma 2025-05-04 14:02:21 +02:00
parent 4124c4d2bb
commit 0342c11fa1
3 changed files with 151 additions and 33 deletions

View File

@ -3,10 +3,24 @@ import { getServerSession } from 'next-auth';
import { authOptions } from '@/app/api/auth/[...nextauth]/route';
import { getObjectContent } from '@/lib/s3';
// Helper function to check authentication
async function checkAuth(request: Request) {
const session = await getServerSession(authOptions);
if (!session?.user?.id) {
console.error('Unauthorized access attempt:', {
url: request.url,
method: request.method,
headers: Object.fromEntries(request.headers)
});
return { authorized: false, userId: null };
}
return { authorized: true, userId: session.user.id };
}
export async function GET(request: Request) {
try {
const session = await getServerSession(authOptions);
if (!session?.user?.id) {
const { authorized, userId } = await checkAuth(request);
if (!authorized || !userId) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
@ -26,12 +40,13 @@ export async function GET(request: Request) {
key = id;
// Ensure the user can only access their own files
if (!key.startsWith(`user-${session.user.id}/`)) {
if (!key.startsWith(`user-${userId}/`)) {
console.error('Unauthorized file access attempt:', { userId, fileId: id });
return NextResponse.json({ error: 'Unauthorized access to file' }, { status: 403 });
}
} else if (path) {
// If a path is provided, ensure it contains the user's ID
if (!path.includes(`/files/cube-${session.user.id}/`) && !path.includes(`user-${session.user.id}/`)) {
if (!path.includes(`/files/cube-${userId}/`) && !path.includes(`user-${userId}/`)) {
// For backward compatibility, convert NextCloud path to S3 path
if (path.startsWith('/files/') || path.includes('/Private/')) {
// Extract folder and filename from path
@ -45,8 +60,10 @@ export async function GET(request: Request) {
else if (path.includes('/Contacts/')) folder = 'contacts';
else if (path.includes('/Health/')) folder = 'health';
key = `user-${session.user.id}/${folder}/${file}`;
key = `user-${userId}/${folder}/${file}`;
console.log('Converted NextCloud path to S3 key:', { path, key });
} else {
console.error('Unauthorized file access attempt:', { userId, filePath: path });
return NextResponse.json({ error: 'Unauthorized access to file' }, { status: 403 });
}
} else {
@ -57,6 +74,8 @@ export async function GET(request: Request) {
return NextResponse.json({ error: 'Invalid parameters' }, { status: 400 });
}
console.log('Fetching file content from S3:', { key });
// Get the file content
const content = await getObjectContent(key);
@ -67,6 +86,6 @@ export async function GET(request: Request) {
return NextResponse.json({ content });
} catch (error) {
console.error('Error fetching file content:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
return NextResponse.json({ error: 'Internal server error', details: error instanceof Error ? error.message : String(error) }, { status: 500 });
}
}

View File

@ -3,52 +3,70 @@ import { getServerSession } from 'next-auth';
import { authOptions } from '@/app/api/auth/[...nextauth]/route';
import { listUserObjects, putObject, deleteObject } from '@/lib/s3';
// Helper function to check authentication
async function checkAuth(request: Request) {
const session = await getServerSession(authOptions);
if (!session?.user?.id) {
console.error('Unauthorized access attempt:', {
url: request.url,
method: request.method,
headers: Object.fromEntries(request.headers)
});
return { authorized: false, userId: null };
}
return { authorized: true, userId: session.user.id };
}
// GET endpoint to list files in a folder
export async function GET(request: Request) {
try {
const session = await getServerSession(authOptions);
if (!session?.user?.id) {
const { authorized, userId } = await checkAuth(request);
if (!authorized || !userId) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const { searchParams } = new URL(request.url);
const folder = searchParams.get('folder');
const folderParam = searchParams.get('folder');
if (!folder) {
if (!folderParam) {
return NextResponse.json({ error: 'Folder parameter is required' }, { status: 400 });
}
// Normalize folder name to lowercase to match S3 convention
const normalizedFolder = folder.toLowerCase();
const normalizedFolder = folderParam.toLowerCase();
// List objects for the user in the specified folder
const files = await listUserObjects(session.user.id, normalizedFolder);
const files = await listUserObjects(userId, normalizedFolder);
return NextResponse.json(files);
} catch (error) {
console.error('Error listing files:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
return NextResponse.json({ error: 'Internal server error', details: error instanceof Error ? error.message : String(error) }, { status: 500 });
}
}
// POST endpoint to create a new file
export async function POST(request: Request) {
try {
const session = await getServerSession(authOptions);
if (!session?.user?.id) {
const { authorized, userId } = await checkAuth(request);
if (!authorized || !userId) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const { title, content, folder } = await request.json();
const body = await request.json().catch(() => ({}));
const { title, content, folder } = body;
if (!title || !content || !folder) {
return NextResponse.json({ error: 'Missing required fields' }, { status: 400 });
return NextResponse.json({ error: 'Missing required fields', received: { title: !!title, content: !!content, folder: !!folder } }, { status: 400 });
}
// Normalize folder name
const normalizedFolder = folder.toLowerCase();
// Create the full key (path) for the S3 object
const key = `user-${session.user.id}/${normalizedFolder}/${title}${title.endsWith('.md') ? '' : '.md'}`;
const key = `user-${userId}/${normalizedFolder}/${title}${title.endsWith('.md') ? '' : '.md'}`;
console.log('Creating file in S3:', { key, contentLength: content.length });
// Save the file to S3
const file = await putObject(key, content);
@ -56,53 +74,56 @@ export async function POST(request: Request) {
return NextResponse.json(file);
} catch (error) {
console.error('Error creating file:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
return NextResponse.json({ error: 'Internal server error', details: error instanceof Error ? error.message : String(error) }, { status: 500 });
}
}
// PUT endpoint to update an existing file
export async function PUT(request: Request) {
try {
const session = await getServerSession(authOptions);
if (!session?.user?.id) {
const { authorized, userId } = await checkAuth(request);
if (!authorized || !userId) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const { id, title, content, folder, mime } = await request.json();
const body = await request.json().catch(() => ({}));
const { id, title, content, folder, mime } = body;
// Check if this is using the direct id (key) or needs to construct one
let key: string;
if (id) {
// Ensure the user can only access their own files
if (!id.startsWith(`user-${session.user.id}/`)) {
if (!id.startsWith(`user-${userId}/`)) {
return NextResponse.json({ error: 'Unauthorized access to file' }, { status: 403 });
}
key = id;
} else {
// If id is not provided, construct it from folder and title
if (!title || !folder) {
return NextResponse.json({ error: 'Missing required fields' }, { status: 400 });
return NextResponse.json({ error: 'Missing required fields', received: { title: !!title, folder: !!folder } }, { status: 400 });
}
const normalizedFolder = folder.toLowerCase();
key = `user-${session.user.id}/${normalizedFolder}/${title}${title.endsWith('.md') ? '' : '.md'}`;
key = `user-${userId}/${normalizedFolder}/${title}${title.endsWith('.md') ? '' : '.md'}`;
}
console.log('Updating file in S3:', { key, contentLength: content?.length });
// Update the file
const file = await putObject(key, content, mime);
return NextResponse.json(file);
} catch (error) {
console.error('Error updating file:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
return NextResponse.json({ error: 'Internal server error', details: error instanceof Error ? error.message : String(error) }, { status: 500 });
}
}
// DELETE endpoint to delete a file
export async function DELETE(request: Request) {
try {
const session = await getServerSession(authOptions);
if (!session?.user?.id) {
const { authorized, userId } = await checkAuth(request);
if (!authorized || !userId) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
@ -114,16 +135,18 @@ export async function DELETE(request: Request) {
}
// Ensure the user can only delete their own files
if (!id.startsWith(`user-${session.user.id}/`)) {
if (!id.startsWith(`user-${userId}/`)) {
return NextResponse.json({ error: 'Unauthorized access to file' }, { status: 403 });
}
console.log('Deleting file from S3:', { key: id });
// Delete the file
await deleteObject(id);
return NextResponse.json({ success: true });
} catch (error) {
console.error('Error deleting file:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
return NextResponse.json({ error: 'Internal server error', details: error instanceof Error ? error.message : String(error) }, { status: 500 });
}
}

View File

@ -2,6 +2,8 @@
import React, { useState, useEffect, useRef } from 'react';
import { Image, FileText, Link, List, Plus } from 'lucide-react';
import { useRouter } from 'next/navigation';
import { useSession } from 'next-auth/react';
interface Note {
id: string;
@ -25,21 +27,39 @@ export const Editor: React.FC<EditorProps> = ({ note, onSave, currentFolder = 'N
const [content, setContent] = useState(note?.content || '');
const [isSaving, setIsSaving] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const saveTimeout = useRef<NodeJS.Timeout>();
const router = useRouter();
const { data: session, status } = useSession();
useEffect(() => {
// Redirect to login if not authenticated
if (status === 'unauthenticated') {
router.push('/signin');
}
}, [status, router]);
useEffect(() => {
const fetchNoteContent = async () => {
if (note?.id) {
setIsLoading(true);
setError(null);
try {
const response = await fetch(`/api/nextcloud/files/content?id=${note.id}`);
if (response.status === 401) {
console.error('Authentication error, redirecting to login');
router.push('/signin');
return;
}
if (!response.ok) {
throw new Error('Failed to fetch note content');
const errorText = await response.text();
throw new Error(`Failed to fetch note content: ${response.status} ${errorText}`);
}
const data = await response.json();
setContent(data.content);
} catch (error) {
console.error('Error fetching note content:', error);
setError('Failed to load note content. Please try again later.');
} finally {
setIsLoading(false);
}
@ -57,7 +77,7 @@ export const Editor: React.FC<EditorProps> = ({ note, onSave, currentFolder = 'N
setTitle('');
setContent('');
}
}, [note]);
}, [note, router]);
const handleTitleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setTitle(e.target.value);
@ -80,12 +100,25 @@ export const Editor: React.FC<EditorProps> = ({ note, onSave, currentFolder = 'N
const handleSave = async () => {
if (!title || !content) return;
if (!session) {
console.error('No active session, cannot save');
setError('You must be logged in to save notes');
return;
}
setIsSaving(true);
setError(null);
try {
const endpoint = note?.id ? '/api/nextcloud/files' : '/api/nextcloud/files';
const method = note?.id ? 'PUT' : 'POST';
console.log('Saving note:', {
id: note?.id,
title,
folder: currentFolder,
contentLength: content.length
});
const response = await fetch(endpoint, {
method,
headers: {
@ -99,11 +132,26 @@ export const Editor: React.FC<EditorProps> = ({ note, onSave, currentFolder = 'N
}),
});
if (response.status === 401) {
console.error('Authentication error, redirecting to login');
router.push('/signin');
return;
}
if (!response.ok) {
throw new Error('Failed to save note');
const errorData = await response.text();
console.error('Failed to save note:', {
status: response.status,
statusText: response.statusText,
data: errorData
});
setError(`Failed to save note: ${response.statusText}`);
throw new Error(`Failed to save note: ${response.status} ${response.statusText}`);
}
const savedNote = await response.json();
console.log('Note saved successfully:', savedNote);
setError(null);
onSave?.({
...savedNote,
content
@ -116,6 +164,27 @@ export const Editor: React.FC<EditorProps> = ({ note, onSave, currentFolder = 'N
}
};
if (!session && status !== 'loading') {
return (
<div className="flex flex-col h-full bg-carnet-bg items-center justify-center">
<div className="text-center">
<h2 className="text-xl font-semibold text-carnet-text-primary mb-2">
Authentication Required
</h2>
<p className="text-carnet-text-muted mb-4">
Please log in to access your notes
</p>
<button
onClick={() => router.push('/signin')}
className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600"
>
Go to Login
</button>
</div>
</div>
);
}
if (!note) {
return (
<div className="flex flex-col h-full bg-carnet-bg items-center justify-center">
@ -145,6 +214,13 @@ export const Editor: React.FC<EditorProps> = ({ note, onSave, currentFolder = 'N
/>
</div>
{/* Error Display */}
{error && (
<div className="p-2 m-2 bg-red-100 border border-red-400 text-red-700 rounded">
{error}
</div>
)}
{/* Editor Area */}
<div className="flex-1 p-4">
{isLoading ? (