diff --git a/app/api/rocket-chat/messages/route.ts b/app/api/rocket-chat/messages/route.ts index 58ea9394..a71a10ce 100644 --- a/app/api/rocket-chat/messages/route.ts +++ b/app/api/rocket-chat/messages/route.ts @@ -56,14 +56,45 @@ export async function GET() { ); } - // Now get user info from Rocket.Chat using the Keycloak username + // Get Rocket.Chat OAuth token + const rocketChatAuthResponse = await fetch( + 'https://parole.slm-lab.net/api/v1/login', + { + method: 'POST', + headers: { + 'Content-Type': 'application/json' + }, + body: JSON.stringify({ + serviceName: 'keycloak', + accessToken: session.accessToken, + expiresIn: 3600 + }) + } + ); + + if (!rocketChatAuthResponse.ok) { + console.error('Rocket.Chat OAuth login error:', { + status: rocketChatAuthResponse.status, + statusText: rocketChatAuthResponse.statusText, + response: await rocketChatAuthResponse.text().catch(() => 'Could not get response text') + }); + return NextResponse.json( + { error: "Failed to authenticate with Rocket.Chat" }, + { status: rocketChatAuthResponse.status } + ); + } + + const rocketChatAuth = await rocketChatAuthResponse.json(); + console.log('Rocket.Chat auth success:', { + userId: rocketChatAuth.data?.userId, + hasToken: !!rocketChatAuth.data?.authToken + }); + + // Now get user info from Rocket.Chat using the obtained token 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 + 'X-Auth-Token': rocketChatAuth.data.authToken, + 'X-User-Id': rocketChatAuth.data.userId }, cache: 'no-store', }); @@ -72,11 +103,6 @@ export async function GET() { 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( @@ -96,11 +122,8 @@ export async function GET() { '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 + 'X-Auth-Token': rocketChatAuth.data.authToken, + 'X-User-Id': rocketChatAuth.data.userId }, cache: 'no-store', } @@ -132,11 +155,8 @@ export async function GET() { `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 + 'X-Auth-Token': rocketChatAuth.data.authToken, + 'X-User-Id': rocketChatAuth.data.userId }, cache: 'no-store', }