NeahFront7/app/api/emails/route.ts
2025-04-13 20:25:47 +02:00

80 lines
2.5 KiB
TypeScript

import { NextRequest, NextResponse } from "next/server";
import { getServerSession } from "next-auth/next";
import { authOptions } from "@/app/api/auth/[...nextauth]/route";
export async function GET(req: NextRequest) {
try {
const session = await getServerSession(authOptions);
if (!session?.user?.email || !session.accessToken) {
return NextResponse.json(
{ error: "Non authentifié" },
{ status: 401 }
);
}
// Get Nextcloud base URL from environment variable
const nextcloudUrl = process.env.NEXTCLOUD_URL;
if (!nextcloudUrl) {
throw new Error("NEXTCLOUD_URL not configured");
}
// Fetch unread messages from Nextcloud Mail API using OIDC token
const response = await fetch(`${nextcloudUrl}/apps/mail/api/v1/messages?filter=unseen`, {
headers: {
'Authorization': `Bearer ${session.accessToken}`,
'Accept': 'application/json',
'OCS-APIRequest': 'true',
'Content-Type': 'application/json',
},
});
if (!response.ok) {
console.error('Failed to fetch emails:', {
status: response.status,
statusText: response.statusText
});
// If token is expired or invalid, return 401
if (response.status === 401) {
return NextResponse.json(
{ error: "Session expirée" },
{ status: 401 }
);
}
throw new Error('Failed to fetch emails from Nextcloud');
}
const data = await response.json();
console.log('Nextcloud mail response:', {
status: response.status,
dataLength: data?.ocs?.data?.length || 0
});
// Transform the response to match our Email interface
const emails = (data?.ocs?.data || []).map((email: any) => ({
id: email.id,
subject: email.subject || '(No subject)',
sender: {
name: email.from?.name || email.from?.email || 'Unknown',
email: email.from?.email || '',
},
date: email.sentDate,
isUnread: true, // Since we're only fetching unread messages
}));
// Sort by date (newest first) and limit to 5 messages
const sortedEmails = emails
.sort((a: any, b: any) => new Date(b.date).getTime() - new Date(a.date).getTime())
.slice(0, 5);
return NextResponse.json(sortedEmails);
} catch (error) {
console.error('Error fetching emails:', error);
return NextResponse.json(
{ error: "Erreur lors de la récupération des emails" },
{ status: 500 }
);
}
}