diff --git a/app/api/auth/[...nextauth]/route.ts b/app/api/auth/[...nextauth]/route.ts index 64e8e471..8c3a7539 100644 --- a/app/api/auth/[...nextauth]/route.ts +++ b/app/api/auth/[...nextauth]/route.ts @@ -82,22 +82,24 @@ export const authOptions: NextAuthOptions = { callbacks: { async jwt({ token, account, profile }) { if (account && profile) { - token.accessToken = account.access_token; - token.refreshToken = account.refresh_token; - token.accessTokenExpires = account.expires_at! * 1000; - // Filter roles consistently - token.role = (profile as any).groups - ?.filter((role: string) => - !role.startsWith('default-roles-') && - !['offline_access', 'uma_authorization'].includes(role) - ) ?? []; - token.username = (profile as any).preferred_username ?? profile.email?.split('@')[0] ?? ''; - token.first_name = (profile as any).given_name ?? ''; - token.last_name = (profile as any).family_name ?? ''; - - // Get Rocket.Chat token for the user using their Keycloak password + // First set the basic token properties + const newToken = { + ...token, + accessToken: account.access_token || '', + refreshToken: account.refresh_token || '', + accessTokenExpires: account.expires_at! * 1000, + role: (profile as any).groups + ?.filter((role: string) => + !role.startsWith('default-roles-') && + !['offline_access', 'uma_authorization'].includes(role) + ) ?? [], + username: (profile as any).preferred_username ?? profile.email?.split('@')[0] ?? '', + first_name: (profile as any).given_name ?? '', + last_name: (profile as any).family_name ?? '', + }; + try { - console.log('Attempting to get personal access tokens for user:', token.username); + console.log('Attempting to get personal access tokens for user:', newToken.username); // First, let's verify the admin token is working const verifyTokenResponse = await fetch('https://parole.slm-lab.net/api/v1/me', { @@ -107,15 +109,9 @@ export const authOptions: NextAuthOptions = { }, }); - console.log('Admin token verification:', { - status: verifyTokenResponse.status, - ok: verifyTokenResponse.ok, - response: await verifyTokenResponse.text().catch(() => 'Could not get response text') - }); - if (!verifyTokenResponse.ok) { console.error('Admin token verification failed'); - return token; + return newToken; } // Get user's personal access tokens using admin credentials @@ -128,22 +124,16 @@ export const authOptions: NextAuthOptions = { }, }); - console.log('Personal access tokens response:', { - status: tokensResponse.status, - ok: tokensResponse.ok, - response: await tokensResponse.text().catch(() => 'Could not get response text') - }); - if (!tokensResponse.ok) { console.error('Failed to get personal access tokens'); - return token; + return newToken; } const tokensData = await tokensResponse.json(); console.log('Parsed tokens data:', tokensData); // Find or create a token for this user - const tokenName = `keycloak-${token.username}`; + const tokenName = `keycloak-${newToken.username}`; let personalToken: string | null = null; let rocketChatUserId: string | null = null; @@ -153,7 +143,7 @@ export const authOptions: NextAuthOptions = { if (existingToken) { console.log('Found existing token:', existingToken); personalToken = existingToken.lastTokenPart; - rocketChatUserId = process.env.ROCKET_CHAT_USER_ID!; // Use admin user ID for now + rocketChatUserId = process.env.ROCKET_CHAT_USER_ID!; } } @@ -173,44 +163,31 @@ export const authOptions: NextAuthOptions = { }), }); - console.log('Create token response:', { - status: createTokenResponse.status, - ok: createTokenResponse.ok, - response: await createTokenResponse.text().catch(() => 'Could not get response text') - }); - if (createTokenResponse.ok) { const createTokenData = await createTokenResponse.json(); console.log('Created token data:', createTokenData); personalToken = createTokenData.token; - rocketChatUserId = process.env.ROCKET_CHAT_USER_ID!; // Use admin user ID for now + rocketChatUserId = process.env.ROCKET_CHAT_USER_ID!; } else { console.error('Failed to create personal access token'); - return token; + return newToken; } } if (personalToken && rocketChatUserId) { - console.log('Setting Rocket.Chat credentials in token:', { - tokenLength: personalToken.length, - userId: rocketChatUserId - }); + console.log('Setting Rocket.Chat credentials in token'); return { - ...token, + ...newToken, rocketChatToken: personalToken, rocketChatUserId: rocketChatUserId, }; - } else { - console.error('Failed to get Rocket.Chat credentials'); - return token; } + return newToken; } catch (error) { console.error('Error in Rocket.Chat authentication:', error); - return token; + return newToken; } - - return token; } // Return previous token if not expired @@ -256,14 +233,11 @@ export const authOptions: NextAuthOptions = { throw new Error("RefreshAccessTokenError"); } - // Ensure all required fields are present - if (!token.rocketChatToken || !token.rocketChatUserId) { - console.error('Missing Rocket.Chat credentials in token:', { - hasToken: !!token.rocketChatToken, - hasUserId: !!token.rocketChatUserId, - token: token - }); - } + console.log('Session callback token:', { + hasRocketChatToken: !!token.rocketChatToken, + hasRocketChatUserId: !!token.rocketChatUserId, + token: token + }); return { ...session,