diff --git a/app/api/auth/[...nextauth]/route.ts b/app/api/auth/[...nextauth]/route.ts index 674c682f..181f1e72 100644 --- a/app/api/auth/[...nextauth]/route.ts +++ b/app/api/auth/[...nextauth]/route.ts @@ -86,6 +86,32 @@ export const authOptions: NextAuthOptions = { 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_URL}/api/users`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'apiKey': process.env.LEANTIME_API_KEY!, + }, + body: JSON.stringify({ + firstname: token.first_name, + lastname: token.last_name, + username: token.username, + email: profile.email, + role: token.role.includes('admin') ? 'admin' : 'user', + }), + }); + + if (!leantimeResponse.ok) { + console.error('Failed to create/update Leantime user:', await leantimeResponse.text()); + } else { + console.log('Successfully created/updated Leantime user'); + } + } catch (error) { + console.error('Error creating/updating Leantime user:', error); + } } // Return previous token if it's not expired @@ -150,6 +176,7 @@ export const authOptions: NextAuthOptions = { 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`, { @@ -164,6 +191,22 @@ export const authOptions: NextAuthOptions = { }), } ); + + // Delete user from Leantime + if (token.username) { + const leantimeResponse = await fetch(`${process.env.LEANTIME_URL}/api/users/${token.username}`, { + method: 'DELETE', + headers: { + 'apiKey': process.env.LEANTIME_API_KEY!, + }, + }); + + if (!leantimeResponse.ok) { + console.error('Failed to delete Leantime user:', await leantimeResponse.text()); + } else { + console.log('Successfully deleted Leantime user'); + } + } } catch (error) { console.error("Error during logout:", error); }