import NextAuth, { NextAuthOptions } from "next-auth"; import KeycloakProvider from "next-auth/providers/keycloak"; interface RocketChatLoginResponse { status: string; data: { authToken: string; userId: string; }; } declare module "next-auth" { interface Session { user: { id: string; name?: string | null; email?: string | null; image?: string | null; username: string; first_name: string; last_name: string; role: string[]; }; accessToken: string; rocketChatToken: string; rocketChatUserId: string; } interface JWT { accessToken: string; refreshToken: string; accessTokenExpires: number; role: string[]; username: string; first_name: string; last_name: string; rocketChatToken: string; rocketChatUserId: string; } } declare module "next-auth/jwt" { interface JWT { accessToken: string; refreshToken: string; accessTokenExpires: number; role: string[]; username: string; first_name: string; last_name: string; rocketChatToken: string; rocketChatUserId: string; } } export const authOptions: NextAuthOptions = { providers: [ KeycloakProvider({ clientId: process.env.KEYCLOAK_CLIENT_ID!, clientSecret: process.env.KEYCLOAK_CLIENT_SECRET!, issuer: process.env.KEYCLOAK_ISSUER!, profile(profile) { // Filter out system roles and only keep valid user roles const validRoles = (profile.groups || []) .filter((role: string) => !role.startsWith('default-roles-') && !['offline_access', 'uma_authorization'].includes(role) ); return { id: profile.sub, name: profile.name ?? profile.preferred_username, email: profile.email, first_name: profile.given_name ?? '', last_name: profile.family_name ?? '', username: profile.preferred_username ?? profile.email?.split('@')[0] ?? '', role: validRoles, } }, }), ], 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 try { const rocketChatResponse = await fetch('https://parole.slm-lab.net/api/v1/login', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ user: token.username, password: account.access_token, // Use the Keycloak access token as password }), }); if (rocketChatResponse.ok) { const rocketChatData = await rocketChatResponse.json() as RocketChatLoginResponse; if (rocketChatData.data) { token.rocketChatToken = rocketChatData.data.authToken; token.rocketChatUserId = rocketChatData.data.userId; } } } catch (error) { console.error('Error getting Rocket.Chat token:', error); } return token; } // Return previous token if not expired if (Date.now() < (token.accessTokenExpires as number)) { return token; } try { const response = await fetch( `${process.env.KEYCLOAK_BASE_URL}/realms/${process.env.KEYCLOAK_REALM}/protocol/openid-connect/token`, { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded", }, body: new URLSearchParams({ grant_type: "refresh_token", client_id: process.env.KEYCLOAK_CLIENT_ID!, client_secret: process.env.KEYCLOAK_CLIENT_SECRET!, refresh_token: token.refreshToken as string, }), } ); const tokens = await response.json(); if (!response.ok) throw tokens; return { ...token, accessToken: tokens.access_token, refreshToken: tokens.refresh_token ?? token.refreshToken, accessTokenExpires: Date.now() + tokens.expires_in * 1000, }; } catch (error) { console.error("Error refreshing token:", error); return { ...token, error: "RefreshAccessTokenError" }; } }, async session({ session, token }) { if (token.error) { throw new Error("RefreshAccessTokenError"); } session.accessToken = token.accessToken; session.rocketChatToken = token.rocketChatToken; session.rocketChatUserId = token.rocketChatUserId; session.user = { ...session.user, id: token.sub as string, first_name: token.first_name ?? '', last_name: token.last_name ?? '', username: token.username ?? '', role: token.role ?? [], }; return session; }, }, events: { async signOut({ token }) { if (token.refreshToken) { try { await fetch( `${process.env.KEYCLOAK_BASE_URL}/realms/${process.env.KEYCLOAK_REALM}/protocol/openid-connect/logout`, { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded", }, body: new URLSearchParams({ client_id: process.env.KEYCLOAK_CLIENT_ID!, client_secret: process.env.KEYCLOAK_CLIENT_SECRET!, refresh_token: token.refreshToken as string, }), } ); } catch (error) { console.error("Error during logout:", error); } } }, }, }; const handler = NextAuth(authOptions); export { handler as GET, handler as POST };