Neah/app/api/proxy/[...path]/route.ts
2025-05-02 16:47:55 +02:00

168 lines
5.9 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth/next';
import { authOptions } from '@/app/api/auth/[...nextauth]/route';
// Map of service prefixes to their base URLs
const SERVICE_URLS: Record<string, string> = {
'parole': process.env.NEXT_PUBLIC_IFRAME_PAROLE_URL || '',
'alma': process.env.NEXT_PUBLIC_IFRAME_AI_ASSISTANT_URL || '',
'crm': process.env.NEXT_PUBLIC_IFRAME_MEDIATIONS_URL || '',
'vision': process.env.NEXT_PUBLIC_IFRAME_CONFERENCE_URL || '',
'showcase': process.env.NEXT_PUBLIC_IFRAME_SHOWCASE_URL || '',
'agilite': process.env.NEXT_PUBLIC_IFRAME_AGILITY_URL || '',
'dossiers': process.env.NEXT_PUBLIC_IFRAME_DRIVE_URL || '',
'the-message': process.env.NEXT_PUBLIC_IFRAME_THEMESSAGE_URL || '',
'qg': process.env.NEXT_PUBLIC_IFRAME_MISSIONVIEW_URL || '',
'design': process.env.NEXT_PUBLIC_IFRAME_DESIGN_URL || '',
'artlab': process.env.NEXT_PUBLIC_IFRAME_DESIGN_URL || ''
};
// Check if a service is Rocket.Chat (they require special authentication)
function isRocketChat(serviceName: string): boolean {
return serviceName === 'parole'; // Assuming 'parole' is your Rocket.Chat service
}
export async function GET(
request: NextRequest,
context: { params: { path: string[] } }
) {
// Get the service prefix (first part of the path)
const paramsObj = await Promise.resolve(context.params);
const pathArray = await Promise.resolve(paramsObj.path);
const serviceName = pathArray[0];
const restOfPath = pathArray.slice(1).join('/');
// Get the base URL for this service
const baseUrl = SERVICE_URLS[serviceName];
if (!baseUrl) {
return NextResponse.json({ error: 'Service not found' }, { status: 404 });
}
// Get the user's session
const session = await getServerSession(authOptions);
if (!session) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
try {
// Extract search parameters
const searchParams = new URL(request.url).searchParams.toString();
const targetUrl = `${baseUrl}/${restOfPath}${searchParams ? `?${searchParams}` : ''}`;
// Prepare headers based on the service type
const headers: Record<string, string> = {};
if (isRocketChat(serviceName)) {
// For Rocket.Chat, use their specific authentication headers
if (session.rocketChatToken && session.rocketChatUserId) {
console.log('Using Rocket.Chat specific authentication');
headers['X-Auth-Token'] = session.rocketChatToken;
headers['X-User-Id'] = session.rocketChatUserId;
} else {
console.warn('Rocket.Chat tokens not available in session');
// Still try with standard authorization if available
if (session.accessToken) {
headers['Authorization'] = `Bearer ${session.accessToken}`;
}
}
} else {
// Standard OAuth Bearer token for other services
if (session.accessToken) {
headers['Authorization'] = `Bearer ${session.accessToken}`;
}
}
// Add other common headers
headers['Accept'] = 'application/json, text/html, */*';
// Forward the request to the target service with the authentication headers
const response = await fetch(targetUrl, { headers });
// Get response data
const data = await response.arrayBuffer();
// Create response with the same status and headers
const newResponse = new NextResponse(data, {
status: response.status,
statusText: response.statusText,
headers: {
'Content-Type': response.headers.get('Content-Type') || 'application/octet-stream',
}
});
return newResponse;
} catch (error) {
console.error('Proxy error:', error);
return NextResponse.json({ error: 'Proxy error' }, { status: 500 });
}
}
export async function POST(
request: NextRequest,
context: { params: { path: string[] } }
) {
// Get the service prefix (first part of the path)
const paramsObj = await Promise.resolve(context.params);
const pathArray = await Promise.resolve(paramsObj.path);
const serviceName = pathArray[0];
const restOfPath = pathArray.slice(1).join('/');
const baseUrl = SERVICE_URLS[serviceName];
if (!baseUrl) {
return NextResponse.json({ error: 'Service not found' }, { status: 404 });
}
const session = await getServerSession(authOptions);
if (!session) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
try {
const searchParams = new URL(request.url).searchParams.toString();
const targetUrl = `${baseUrl}/${restOfPath}${searchParams ? `?${searchParams}` : ''}`;
// Get the request body
const body = await request.arrayBuffer();
// Prepare headers based on the service type
const headers: Record<string, string> = {
'Content-Type': request.headers.get('Content-Type') || 'application/json',
};
if (isRocketChat(serviceName)) {
// For Rocket.Chat, use their specific authentication headers
if (session.rocketChatToken && session.rocketChatUserId) {
headers['X-Auth-Token'] = session.rocketChatToken;
headers['X-User-Id'] = session.rocketChatUserId;
} else if (session.accessToken) {
headers['Authorization'] = `Bearer ${session.accessToken}`;
}
} else {
// Standard OAuth Bearer token for other services
if (session.accessToken) {
headers['Authorization'] = `Bearer ${session.accessToken}`;
}
}
const response = await fetch(targetUrl, {
method: 'POST',
headers,
body: body
});
const data = await response.arrayBuffer();
return new NextResponse(data, {
status: response.status,
statusText: response.statusText,
headers: {
'Content-Type': response.headers.get('Content-Type') || 'application/octet-stream',
}
});
} catch (error) {
console.error('Proxy error:', error);
return NextResponse.json({ error: 'Proxy error' }, { status: 500 });
}
}