diff --git a/app/api/users/[userId]/route.ts b/app/api/users/[userId]/route.ts index e0190cde..9bdd8937 100644 --- a/app/api/users/[userId]/route.ts +++ b/app/api/users/[userId]/route.ts @@ -2,9 +2,78 @@ import { getServerSession } from "next-auth/next"; import { authOptions } from "@/app/api/auth/[...nextauth]/route"; import { NextResponse } from "next/server"; -// Helper function to delete user from Leantime -async function deleteLeantimeUser(userId: string): Promise<{ success: boolean; error?: string }> { +// Helper function to get Leantime user ID by email +async function getLeantimeUserId(email: string): Promise { try { + const response = await fetch('https://agilite.slm-lab.net/api/jsonrpc', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'X-API-Key': process.env.LEANTIME_TOKEN || '', + }, + body: JSON.stringify({ + method: 'leantime.rpc.Users.Users.usernameExist', + jsonrpc: '2.0', + id: 1, + params: { + username: email, + notUserId: 0 + } + }) + }); + + const data = await response.json(); + console.log('Leantime username check response:', data); + + if (!response.ok || !data.result) { + console.error('Failed to check Leantime user:', data); + return null; + } + + // If user exists, get their ID + const userResponse = await fetch('https://agilite.slm-lab.net/api/jsonrpc', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'X-API-Key': process.env.LEANTIME_TOKEN || '', + }, + body: JSON.stringify({ + method: 'leantime.rpc.Users.Users.getUserByEmail', + jsonrpc: '2.0', + id: 1, + params: { + email: email + } + }) + }); + + const userData = await userResponse.json(); + console.log('Leantime get user response:', userData); + + if (!userResponse.ok || !userData.result) { + console.error('Failed to get Leantime user:', userData); + return null; + } + + return userData.result.id; + } catch (error) { + console.error('Error getting Leantime user:', error); + return null; + } +} + +// Helper function to delete user from Leantime +async function deleteLeantimeUser(email: string): Promise<{ success: boolean; error?: string }> { + try { + // First get the Leantime user ID + const leantimeUserId = await getLeantimeUserId(email); + if (!leantimeUserId) { + return { + success: false, + error: 'User not found in Leantime' + }; + } + const response = await fetch('https://agilite.slm-lab.net/api/jsonrpc', { method: 'POST', headers: { @@ -16,7 +85,7 @@ async function deleteLeantimeUser(userId: string): Promise<{ success: boolean; e jsonrpc: '2.0', id: 1, params: { - id: userId + id: leantimeUserId } }) });