diff --git a/app/api/rocket-chat/messages/route.ts b/app/api/rocket-chat/messages/route.ts index 7db08f55..3d97f509 100644 --- a/app/api/rocket-chat/messages/route.ts +++ b/app/api/rocket-chat/messages/route.ts @@ -98,14 +98,32 @@ export async function GET(request: Request) { id: currentUser._id }); - // Step 3: Use admin token for all requests + // Step 3: Create a token for the current user + const createTokenResponse = await fetch(`${baseUrl}/api/v1/users.createToken`, { + method: 'POST', + headers: adminHeaders, + body: JSON.stringify({ + userId: currentUser._id + }) + }); + + if (!createTokenResponse.ok) { + console.error('Failed to create user token:', createTokenResponse.status); + const errorText = await createTokenResponse.text(); + console.error('Create token error details:', errorText); + return NextResponse.json({ messages: [] }, { status: 200 }); + } + + const tokenData = await createTokenResponse.json(); + + // Use the user's token for subsequent requests const userHeaders = { - 'X-Auth-Token': process.env.ROCKET_CHAT_TOKEN!, - 'X-User-Id': process.env.ROCKET_CHAT_USER_ID!, + 'X-Auth-Token': tokenData.data.authToken, + 'X-User-Id': currentUser._id, 'Content-Type': 'application/json' }; - // Step 4: Get user's subscriptions + // Step 4: Get user's subscriptions using user token const subscriptionsResponse = await fetch(`${baseUrl}/api/v1/subscriptions.get`, { method: 'GET', headers: userHeaders @@ -150,7 +168,7 @@ export async function GET(request: Request) { const messages: any[] = []; const processedRooms = new Set(); - // Step 5: Fetch messages + // Step 5: Fetch messages using user token for (const subscription of userSubscriptions) { if (messages.length >= 7 || processedRooms.has(subscription._id)) continue; processedRooms.add(subscription._id); @@ -159,7 +177,7 @@ export async function GET(request: Request) { // Determine the correct endpoint based on room type const endpoint = subscription.t === 'c' ? 'channels.messages' : 'im.messages'; - // Get the latest messages from the room + // Get the latest messages from the room using user token const messagesResponse = await fetch( `${baseUrl}/api/v1/${endpoint}?roomId=${subscription.rid}&count=1`, { method: 'GET',