176 lines
5.6 KiB
TypeScript
176 lines
5.6 KiB
TypeScript
import { getServerSession } from "next-auth";
|
|
import { authOptions } from "@/app/api/auth/[...nextauth]/route";
|
|
import { NextResponse } from "next/server";
|
|
|
|
export async function GET() {
|
|
try {
|
|
const session = await getServerSession(authOptions);
|
|
if (!session) {
|
|
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
|
}
|
|
|
|
// Debug log to see all session data
|
|
console.log('Session data:', {
|
|
user: session.user,
|
|
accessToken: session.accessToken ? 'present' : 'missing'
|
|
});
|
|
|
|
if (!session.accessToken) {
|
|
return NextResponse.json({ error: "No access token found" }, { status: 401 });
|
|
}
|
|
|
|
// First get the username from Keycloak
|
|
const keycloakResponse = await fetch(
|
|
`${process.env.KEYCLOAK_BASE_URL}/realms/${process.env.KEYCLOAK_REALM}/protocol/openid-connect/userinfo`,
|
|
{
|
|
headers: {
|
|
'Authorization': `Bearer ${session.accessToken}`
|
|
}
|
|
}
|
|
);
|
|
|
|
if (!keycloakResponse.ok) {
|
|
console.error('Failed to get Keycloak user info:', {
|
|
status: keycloakResponse.status,
|
|
statusText: keycloakResponse.statusText,
|
|
response: await keycloakResponse.text().catch(() => 'Could not get response text')
|
|
});
|
|
return NextResponse.json(
|
|
{ error: "Failed to get user info from Keycloak" },
|
|
{ status: keycloakResponse.status }
|
|
);
|
|
}
|
|
|
|
const keycloakUser = await keycloakResponse.json();
|
|
const username = keycloakUser.preferred_username;
|
|
|
|
console.log('Keycloak user info:', {
|
|
username,
|
|
sub: keycloakUser.sub
|
|
});
|
|
|
|
if (!username) {
|
|
return NextResponse.json(
|
|
{ error: "No username found in Keycloak user info" },
|
|
{ status: 400 }
|
|
);
|
|
}
|
|
|
|
// Now get user info from Rocket.Chat using the Keycloak username
|
|
const meResponse = await fetch('https://parole.slm-lab.net/api/v1/me', {
|
|
headers: {
|
|
'Authorization': `Bearer ${session.accessToken}`,
|
|
'X-Auth-Token': session.accessToken,
|
|
'X-User-Id': keycloakUser.sub,
|
|
'X-Oauth-User': username,
|
|
'X-OAuth-Username': username
|
|
},
|
|
cache: 'no-store',
|
|
});
|
|
|
|
if (!meResponse.ok) {
|
|
console.error('Rocket.Chat me error:', {
|
|
status: meResponse.status,
|
|
statusText: meResponse.statusText,
|
|
headers: {
|
|
'X-Oauth-User': username,
|
|
'X-OAuth-Username': username,
|
|
'Authorization': 'Bearer [hidden]'
|
|
},
|
|
response: await meResponse.text().catch(() => 'Could not get response text')
|
|
});
|
|
return NextResponse.json(
|
|
{ error: "Failed to get user info from Rocket.Chat" },
|
|
{ status: meResponse.status }
|
|
);
|
|
}
|
|
|
|
const userData = await meResponse.json();
|
|
console.log('Rocket.Chat user data:', {
|
|
userId: userData._id,
|
|
username: userData.username
|
|
});
|
|
|
|
// Get the user's subscriptions (rooms they are in)
|
|
const subscriptionsResponse = await fetch(
|
|
'https://parole.slm-lab.net/api/v1/subscriptions.get',
|
|
{
|
|
headers: {
|
|
'Authorization': `Bearer ${session.accessToken}`,
|
|
'X-Auth-Token': session.accessToken,
|
|
'X-User-Id': userData._id,
|
|
'X-Oauth-User': username,
|
|
'X-OAuth-Username': username
|
|
},
|
|
cache: 'no-store',
|
|
}
|
|
);
|
|
|
|
if (!subscriptionsResponse.ok) {
|
|
console.error('Rocket.Chat subscriptions error:', {
|
|
status: subscriptionsResponse.status,
|
|
statusText: subscriptionsResponse.statusText,
|
|
response: await subscriptionsResponse.text().catch(() => 'Could not get response text')
|
|
});
|
|
return NextResponse.json(
|
|
{ error: "Failed to fetch subscriptions" },
|
|
{ status: subscriptionsResponse.status }
|
|
);
|
|
}
|
|
|
|
const subscriptions = await subscriptionsResponse.json();
|
|
if (!subscriptions.update || subscriptions.update.length === 0) {
|
|
return NextResponse.json({ messages: [] });
|
|
}
|
|
|
|
// Get the last message from each room
|
|
const messages = await Promise.all(
|
|
subscriptions.update.map(async (room: any) => {
|
|
if (!room.lastMessage?._id) return null;
|
|
|
|
const messageResponse = await fetch(
|
|
`https://parole.slm-lab.net/api/v1/chat.getMessage?msgId=${room.lastMessage._id}`,
|
|
{
|
|
headers: {
|
|
'Authorization': `Bearer ${session.accessToken}`,
|
|
'X-Auth-Token': session.accessToken,
|
|
'X-User-Id': userData._id,
|
|
'X-Oauth-User': username,
|
|
'X-OAuth-Username': username
|
|
},
|
|
cache: 'no-store',
|
|
}
|
|
);
|
|
|
|
if (messageResponse.ok) {
|
|
const messageData = await messageResponse.json();
|
|
return {
|
|
...messageData.message,
|
|
roomName: room.name || 'Direct Message',
|
|
roomType: room.t,
|
|
};
|
|
}
|
|
console.error('Failed to fetch message:', {
|
|
roomId: room._id,
|
|
messageId: room.lastMessage._id,
|
|
status: messageResponse.status,
|
|
response: await messageResponse.text().catch(() => 'Could not get response text')
|
|
});
|
|
return null;
|
|
})
|
|
);
|
|
|
|
// Filter out any null messages and sort by timestamp
|
|
const validMessages = messages
|
|
.filter((msg): msg is NonNullable<typeof msg> => msg !== null)
|
|
.sort((a, b) => new Date(b.ts).getTime() - new Date(a.ts).getTime());
|
|
|
|
return NextResponse.json({ messages: validMessages });
|
|
} catch (error) {
|
|
console.error('Error fetching messages:', error);
|
|
return NextResponse.json(
|
|
{ error: "Internal server error" },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
}
|