From 71d3670a6f0b20d758029c1babadf412fc17d20b Mon Sep 17 00:00:00 2001 From: Alma Date: Sat, 12 Apr 2025 10:22:41 +0200 Subject: [PATCH] correction flow 5 --- app/api/auth/[...nextauth]/route.ts | 140 ++++------------------------ 1 file changed, 20 insertions(+), 120 deletions(-) diff --git a/app/api/auth/[...nextauth]/route.ts b/app/api/auth/[...nextauth]/route.ts index 1289bb40..ee697ab8 100644 --- a/app/api/auth/[...nextauth]/route.ts +++ b/app/api/auth/[...nextauth]/route.ts @@ -1,14 +1,6 @@ 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: { @@ -22,8 +14,6 @@ declare module "next-auth" { role: string[]; }; accessToken: string; - rocketChatToken: string; - rocketChatUserId: string; } interface JWT { @@ -34,22 +24,6 @@ declare module "next-auth" { 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; } } @@ -67,72 +41,29 @@ export const authOptions: NextAuthOptions = { first_name: profile.given_name ?? '', last_name: profile.family_name ?? '', username: profile.preferred_username ?? profile.email?.split('@')[0] ?? '', - role: profile.groups || [], + role: profile.groups ?? [], } }, }), ], callbacks: { async jwt({ token, account, profile }) { - console.log('JWT callback called with:', { token, account, profile }); - - // Initial sign in if (account && profile) { - // Set user data from profile - token.username = profile.preferred_username || ''; - token.first_name = profile.given_name || ''; - token.last_name = profile.family_name || ''; - token.role = profile.groups || []; - token.accessToken = account.access_token || ''; - token.refreshToken = account.refresh_token || ''; - token.accessTokenExpires = account.expires_at ? account.expires_at * 1000 : Date.now() + 60 * 60 * 1000; - - // Create or update Leantime user - try { - const leantimeResponse = await fetch(`${process.env.LEANTIME_API_URL}/api/jsonrpc`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - 'x-api-key': process.env.LEANTIME_API_KEY!, - }, - body: JSON.stringify({ - method: 'leantime.rpc.Users.Users.addUser', - jsonrpc: '2.0', - id: 1, - params: { - values: { - firstname: token.first_name, - lastname: token.last_name, - username: token.username, - email: profile.email, - role: token.role.includes('admin') ? 'admin' : 'user', - password: Math.random().toString(36).slice(-8), // Generate a random password - status: 'a', // Active status - source: 'keycloak', - } - } - }), - }); - - const responseData = await leantimeResponse.json(); - console.log('Leantime response:', responseData); - - if (!leantimeResponse.ok || !responseData.result) { - console.error('Failed to create/update Leantime user:', responseData); - } else { - console.log('Successfully created/updated Leantime user with ID:', responseData.result); - } - } catch (error) { - console.error('Error creating/updating Leantime user:', error); - } + token.accessToken = account.access_token; + token.refreshToken = account.refresh_token; + token.accessTokenExpires = account.expires_at! * 1000; + token.role = (profile as any).groups ?? []; + 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 ?? ''; + return token; } - // Return previous token if it's not expired + // Return previous token if not expired if (Date.now() < (token.accessTokenExpires as number)) { return token; } - // Token refresh case try { const response = await fetch( `${process.env.KEYCLOAK_BASE_URL}/realms/${process.env.KEYCLOAK_REALM}/protocol/openid-connect/token`, @@ -145,7 +76,7 @@ export const authOptions: NextAuthOptions = { grant_type: "refresh_token", client_id: process.env.KEYCLOAK_CLIENT_ID!, client_secret: process.env.KEYCLOAK_CLIENT_SECRET!, - refresh_token: token.refreshToken, + refresh_token: token.refreshToken as string, }), } ); @@ -171,25 +102,22 @@ export const authOptions: NextAuthOptions = { throw new Error("RefreshAccessTokenError"); } - return { - ...session, - accessToken: token.accessToken, - user: { - ...session.user, - id: token.sub as string, - first_name: token.first_name || '', - last_name: token.last_name || '', - username: token.username || '', - role: token.role || [], - }, + session.accessToken = token.accessToken; + 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 { - // Logout from Keycloak await fetch( `${process.env.KEYCLOAK_BASE_URL}/realms/${process.env.KEYCLOAK_REALM}/protocol/openid-connect/logout`, { @@ -204,34 +132,6 @@ export const authOptions: NextAuthOptions = { }), } ); - - // Delete user from Leantime - if (token.username) { - const leantimeResponse = await fetch(`${process.env.LEANTIME_API_URL}/api/jsonrpc`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - 'x-api-key': process.env.LEANTIME_API_KEY!, - }, - body: JSON.stringify({ - method: 'leantime.rpc.Users.Users.deleteUser', - jsonrpc: '2.0', - id: 1, - params: { - id: token.username - } - }), - }); - - const responseData = await leantimeResponse.json(); - console.log('Leantime delete response:', responseData); - - if (!leantimeResponse.ok || !responseData.result) { - console.error('Failed to delete Leantime user:', responseData); - } else { - console.log('Successfully deleted Leantime user'); - } - } } catch (error) { console.error("Error during logout:", error); }