diff --git a/app/api/auth/[...nextauth]/route.ts b/app/api/auth/[...nextauth]/route.ts index 87053f84..fb64e0d1 100644 --- a/app/api/auth/[...nextauth]/route.ts +++ b/app/api/auth/[...nextauth]/route.ts @@ -84,13 +84,8 @@ export const authOptions: NextAuthOptions = { console.log('JWT callback called with:', { token, account, profile }); if (account && profile) { - // Find or create a token for this user - const tokenName = `keycloak-${token.username}`; - let personalToken: string | null = null; - let rocketChatUserId: string | null = null; - // First, get the user's Rocket.Chat ID - const userInfoResponse = await fetch(`https://parole.slm-lab.net/api/v1/users.info?username=${token.username}`, { + const userInfoResponse = await fetch(`${process.env.ROCKET_CHAT_URL}/api/v1/users.info?username=${token.username}`, { headers: { 'X-Auth-Token': process.env.ROCKET_CHAT_TOKEN!, 'X-User-Id': process.env.ROCKET_CHAT_USER_ID!, @@ -105,16 +100,16 @@ export const authOptions: NextAuthOptions = { const userInfo = await userInfoResponse.json(); console.log('User info from Rocket.Chat:', userInfo); - if (userInfo.user && userInfo.user._id) { - rocketChatUserId = userInfo.user._id; - console.log('Found user ID:', rocketChatUserId); - } else { + if (!userInfo.user || !userInfo.user._id) { console.error('No user ID found in Rocket.Chat response'); return token; } - // Get user's personal access tokens using admin credentials - const tokensResponse = await fetch('https://parole.slm-lab.net/api/v1/users.getPersonalAccessTokens', { + const rocketChatUserId = userInfo.user._id; + console.log('Found user ID:', rocketChatUserId); + + // Get user's personal access tokens + const tokensResponse = await fetch(`${process.env.ROCKET_CHAT_URL}/api/v1/users.getPersonalAccessTokens`, { method: 'GET', headers: { 'X-Auth-Token': process.env.ROCKET_CHAT_TOKEN!, @@ -131,8 +126,10 @@ export const authOptions: NextAuthOptions = { const tokensData = await tokensResponse.json(); console.log('Parsed tokens data:', tokensData); + let personalToken = null; + const tokenName = `keycloak-${token.username}`; + if (tokensData.tokens && tokensData.tokens.length > 0) { - // Use existing token const existingToken = tokensData.tokens.find((t: any) => t.name === tokenName); if (existingToken) { console.log('Found existing token:', existingToken); @@ -142,8 +139,7 @@ export const authOptions: NextAuthOptions = { if (!personalToken) { console.log('Creating new personal access token'); - // Create new token - const createTokenResponse = await fetch('https://parole.slm-lab.net/api/v1/users.generatePersonalAccessToken', { + const createTokenResponse = await fetch(`${process.env.ROCKET_CHAT_URL}/api/v1/users.generatePersonalAccessToken`, { method: 'POST', headers: { 'X-Auth-Token': process.env.ROCKET_CHAT_TOKEN!, diff --git a/app/api/rocket-chat/messages/route.ts b/app/api/rocket-chat/messages/route.ts index 2fa29418..0c853240 100644 --- a/app/api/rocket-chat/messages/route.ts +++ b/app/api/rocket-chat/messages/route.ts @@ -2,162 +2,108 @@ 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) { - console.error('No session found'); - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); - } +export async function GET(request: Request) { + const session = await getServerSession(authOptions); + + if (!session) { + console.error('No session found'); + return new Response(JSON.stringify({ error: 'Unauthorized' }), { + status: 401, + headers: { 'Content-Type': 'application/json' }, + }); + } - console.log('Session data:', { + console.log('Session data:', { + hasToken: !!session.rocketChatToken, + hasUserId: !!session.rocketChatUserId, + tokenLength: session.rocketChatToken?.length, + userIdLength: session.rocketChatUserId?.length, + username: session.user?.username + }); + + if (!session.rocketChatToken || !session.rocketChatUserId) { + console.error('Missing Rocket.Chat credentials in session:', { hasToken: !!session.rocketChatToken, hasUserId: !!session.rocketChatUserId, - tokenLength: session.rocketChatToken?.length, - userIdLength: session.rocketChatUserId?.length + username: session.user?.username + }); + return new Response(JSON.stringify({ error: 'Missing Rocket.Chat credentials' }), { + status: 401, + headers: { 'Content-Type': 'application/json' }, + }); + } + + try { + // Get user's subscriptions + const subscriptionsResponse = await fetch(`${process.env.ROCKET_CHAT_URL}/api/v1/subscriptions.get`, { + headers: { + 'X-Auth-Token': session.rocketChatToken, + 'X-User-Id': session.rocketChatUserId, + }, }); - // Get the user's Rocket.Chat token from their session - const rocketChatToken = session.rocketChatToken; - const rocketChatUserId = session.rocketChatUserId; - - if (!rocketChatToken || !rocketChatUserId) { - console.error('Missing Rocket.Chat credentials in session:', { - hasToken: !!rocketChatToken, - hasUserId: !!rocketChatUserId, - session: session - }); - return NextResponse.json({ error: "User not authenticated with Rocket.Chat" }, { status: 401 }); - } - - // Get the user's subscriptions (rooms they are in) - const subscriptionsResponse = await fetch( - 'https://parole.slm-lab.net/api/v1/subscriptions.get', - { - headers: { - 'X-Auth-Token': rocketChatToken, - 'X-User-Id': rocketChatUserId, - 'Content-Type': 'application/json' - } - } - ); - if (!subscriptionsResponse.ok) { - console.error('Rocket.Chat subscriptions error:', { + console.error('Failed to get subscriptions:', { status: subscriptionsResponse.status, statusText: subscriptionsResponse.statusText, - response: await subscriptionsResponse.text().catch(() => 'Could not get response text') + username: session.user?.username + }); + return new Response(JSON.stringify({ error: 'Failed to get subscriptions' }), { + status: subscriptionsResponse.status, + headers: { 'Content-Type': 'application/json' }, }); - return NextResponse.json( - { error: "Failed to fetch subscriptions" }, - { status: subscriptionsResponse.status } - ); } - const subscriptions = await subscriptionsResponse.json(); - console.log('Subscriptions response:', subscriptions); + const subscriptionsData = await subscriptionsResponse.json(); + console.log('Subscriptions response:', subscriptionsData); - if (!subscriptions.update || subscriptions.update.length === 0) { - console.log('No subscriptions found'); - return NextResponse.json({ messages: [] }); - } + const messages: any[] = []; - // Get the last message from each room - const messages = await Promise.all( - subscriptions.update.map(async (subscription: any) => { - try { - if (!subscription.rid) { - console.log('No room ID found for subscription:', subscription); - return null; - } - - // Choose the appropriate endpoint based on room type - const endpoint = subscription.t === 'd' - ? 'im.messages' - : subscription.t === 'c' - ? 'channels.messages' - : 'groups.messages'; - - console.log(`Fetching messages for room ${subscription.name} using endpoint ${endpoint}`); - - // Get the most recent messages from the room using the user's personal access token - const messagesResponse = await fetch( - `https://parole.slm-lab.net/api/v1/${endpoint}?roomId=${subscription.rid}&count=1`, - { - headers: { - 'X-Auth-Token': rocketChatToken, - 'X-User-Id': rocketChatUserId, - 'Content-Type': 'application/json' - } - } - ); - - if (!messagesResponse.ok) { - console.error('Failed to fetch messages:', { - roomId: subscription.rid, - endpoint, - status: messagesResponse.status, - response: await messagesResponse.text().catch(() => 'Could not get response text') - }); - return null; - } - - const messagesData = await messagesResponse.json(); - console.log(`Messages response for ${subscription.name}:`, { - count: messagesData.messages?.length, - success: messagesData.success - }); - - if (messagesData.messages && messagesData.messages.length > 0) { - const message = messagesData.messages[0]; - - // For direct messages, check if the room ID contains the user's ID - if (subscription.t === 'd') { - // Extract the other user's ID from the room ID - const roomIdParts = subscription.rid.split(rocketChatUserId); - const otherUserId = roomIdParts[0] || roomIdParts[1]; - - // Only include messages where the user is either the sender or the recipient - if (message.u._id === rocketChatUserId || message.u._id === otherUserId) { - return { - ...message, - roomName: subscription.fname || subscription.name || 'Direct Message', - roomType: subscription.t, - }; - } - } else { - // For channels and groups, only include messages where the user is the sender - if (message.u._id === rocketChatUserId) { - return { - ...message, - roomName: subscription.fname || subscription.name || 'Direct Message', - roomType: subscription.t, - }; - } - } - } - - console.log('No messages found for room:', subscription.rid); - return null; - } catch (error) { - console.error('Error processing room:', subscription.rid, error); - return null; + for (const subscription of subscriptionsData.update) { + console.log(`Fetching messages for room ${subscription.name} using endpoint ${subscription.t === 'c' ? 'channels.messages' : 'im.messages'}`); + + const endpoint = subscription.t === 'c' ? 'channels.messages' : 'im.messages'; + const roomId = subscription.t === 'c' ? subscription.name : subscription.rid; + + const messagesResponse = await fetch( + `${process.env.ROCKET_CHAT_URL}/api/v1/${endpoint}?roomId=${roomId}`, + { + headers: { + 'X-Auth-Token': session.rocketChatToken, + 'X-User-Id': session.rocketChatUserId, + }, } - }) - ); + ); - // Filter out any null messages and sort by timestamp - const validMessages = messages - .filter((msg): msg is NonNullable => msg !== null) - .sort((a, b) => new Date(b.ts).getTime() - new Date(a.ts).getTime()); + if (!messagesResponse.ok) { + console.error(`Failed to get messages for room ${subscription.name}:`, { + status: messagesResponse.status, + statusText: messagesResponse.statusText, + username: session.user?.username + }); + continue; + } - console.log('Found messages:', validMessages.length); - return NextResponse.json({ messages: validMessages }); + const messagesData = await messagesResponse.json(); + console.log(`Messages response for ${subscription.name}:`, messagesData); + + if (messagesData.messages && messagesData.messages.length > 0) { + messages.push(...messagesData.messages); + } else { + console.log(`No messages found for room: ${roomId}`); + } + } + + console.log('Found messages:', messages.length); + return new Response(JSON.stringify({ messages }), { + status: 200, + headers: { 'Content-Type': 'application/json' }, + }); } catch (error) { console.error('Error fetching messages:', error); - return NextResponse.json( - { error: "Internal server error" }, - { status: 500 } - ); + return new Response(JSON.stringify({ error: 'Internal server error' }), { + status: 500, + headers: { 'Content-Type': 'application/json' }, + }); } } \ No newline at end of file