|
1 | | -import { account, db, user } from '@sim/db' |
2 | | -import { createLogger } from '@sim/logger' |
3 | | -import { eq } from 'drizzle-orm' |
4 | | -import { decodeJwt } from 'jose' |
5 | | -import { type NextRequest, NextResponse } from 'next/server' |
6 | | -import type { OAuthConnection } from '@/lib/api/contracts/oauth-connections' |
7 | | -import { getSession } from '@/lib/auth' |
8 | | -import { generateRequestId } from '@/lib/core/utils/request' |
9 | | -import { withRouteHandler } from '@/lib/core/utils/with-route-handler' |
10 | | -import type { OAuthProvider } from '@/lib/oauth' |
11 | | -import { parseProvider } from '@/lib/oauth' |
12 | | - |
13 | | -const logger = createLogger('OAuthConnectionsAPI') |
14 | | - |
15 | | -interface GoogleIdToken { |
16 | | - email?: string |
17 | | - sub?: string |
18 | | - name?: string |
19 | | -} |
20 | | - |
21 | | -/** |
22 | | - * Get all OAuth connections for the current user |
23 | | - */ |
24 | | -export const GET = withRouteHandler(async (request: NextRequest) => { |
25 | | - const requestId = generateRequestId() |
26 | | - |
27 | | - try { |
28 | | - // Get the session |
29 | | - const session = await getSession() |
30 | | - |
31 | | - // Check if the user is authenticated |
32 | | - if (!session?.user?.id) { |
33 | | - logger.warn(`[${requestId}] Unauthenticated request rejected`) |
34 | | - return NextResponse.json({ error: 'User not authenticated' }, { status: 401 }) |
35 | | - } |
36 | | - |
37 | | - // Get all accounts for this user |
38 | | - const accounts = await db.select().from(account).where(eq(account.userId, session.user.id)) |
39 | | - |
40 | | - // Get the user's email for fallback |
41 | | - const userRecord = await db |
42 | | - .select({ email: user.email }) |
43 | | - .from(user) |
44 | | - .where(eq(user.id, session.user.id)) |
45 | | - .limit(1) |
46 | | - |
47 | | - const userEmail = userRecord.length > 0 ? userRecord[0]?.email : null |
48 | | - |
49 | | - // Process accounts to determine connections |
50 | | - const connections: OAuthConnection[] = [] |
51 | | - |
52 | | - for (const acc of accounts) { |
53 | | - const { baseProvider, featureType } = parseProvider(acc.providerId as OAuthProvider) |
54 | | - const scopes = acc.scope ? acc.scope.split(/\s+/).filter(Boolean) : [] |
55 | | - |
56 | | - if (baseProvider) { |
57 | | - // Try multiple methods to get a user-friendly display name |
58 | | - let displayName = '' |
59 | | - |
60 | | - // Method 1: Try to extract email from ID token (works for Google, etc.) |
61 | | - if (acc.idToken) { |
62 | | - try { |
63 | | - const decoded = decodeJwt<GoogleIdToken>(acc.idToken) |
64 | | - if (decoded.email) { |
65 | | - displayName = decoded.email |
66 | | - } else if (decoded.name) { |
67 | | - displayName = decoded.name |
68 | | - } |
69 | | - } catch (_error) { |
70 | | - logger.warn(`[${requestId}] Error decoding ID token`, { |
71 | | - accountId: acc.id, |
72 | | - }) |
73 | | - } |
74 | | - } |
75 | | - |
76 | | - // Method 2: For GitHub, the accountId might be the username |
77 | | - if (!displayName && baseProvider === 'github') { |
78 | | - displayName = `${acc.accountId} (GitHub)` |
79 | | - } |
80 | | - |
81 | | - // Method 3: Use the user's email from our database |
82 | | - if (!displayName && userEmail) { |
83 | | - displayName = userEmail |
84 | | - } |
85 | | - |
86 | | - // Fallback: Use accountId with provider type as context |
87 | | - if (!displayName) { |
88 | | - displayName = `${acc.accountId} (${baseProvider})` |
89 | | - } |
90 | | - |
91 | | - // Create a unique connection key that includes the full provider ID |
92 | | - const connectionKey = acc.providerId |
93 | | - |
94 | | - // Find existing connection for this specific provider ID |
95 | | - const existingConnection = connections.find((conn) => conn.provider === connectionKey) |
96 | | - |
97 | | - const accountSummary = { |
98 | | - id: acc.id, |
99 | | - name: displayName, |
100 | | - } |
101 | | - |
102 | | - if (existingConnection) { |
103 | | - // Add account to existing connection |
104 | | - existingConnection.accounts = existingConnection.accounts || [] |
105 | | - existingConnection.accounts.push(accountSummary) |
106 | | - |
107 | | - existingConnection.scopes = Array.from( |
108 | | - new Set([...(existingConnection.scopes || []), ...scopes]) |
109 | | - ) |
110 | | - |
111 | | - const existingTimestamp = existingConnection.lastConnected |
112 | | - ? new Date(existingConnection.lastConnected).getTime() |
113 | | - : 0 |
114 | | - const candidateTimestamp = acc.updatedAt.getTime() |
115 | | - |
116 | | - if (candidateTimestamp > existingTimestamp) { |
117 | | - existingConnection.lastConnected = acc.updatedAt.toISOString() |
118 | | - } |
119 | | - } else { |
120 | | - // Create new connection |
121 | | - connections.push({ |
122 | | - provider: connectionKey, |
123 | | - baseProvider, |
124 | | - featureType, |
125 | | - isConnected: true, |
126 | | - scopes, |
127 | | - lastConnected: acc.updatedAt.toISOString(), |
128 | | - accounts: [accountSummary], |
129 | | - }) |
130 | | - } |
131 | | - } |
132 | | - } |
133 | | - |
134 | | - return NextResponse.json({ connections }, { status: 200 }) |
135 | | - } catch (error) { |
136 | | - logger.error(`[${requestId}] Error fetching OAuth connections`, error) |
137 | | - return NextResponse.json({ error: 'Internal server error' }, { status: 500 }) |
138 | | - } |
| 1 | +import { listOAuthConnectionsContract } from '@/lib/api/contracts/oauth-connections' |
| 2 | +import { |
| 3 | + defineInternalJsonRoute, |
| 4 | + internalRateLimits, |
| 5 | + internalSessionAuth, |
| 6 | +} from '@/lib/api/server/routes' |
| 7 | +import { internalCredentialErrorPolicy } from '@/lib/credentials/api/route-policies' |
| 8 | +import { listOAuthConnectionsUseCase } from '@/lib/credentials/application/oauth-accounts' |
| 9 | +import { credentialUserOperations } from '@/lib/credentials/application/operations' |
| 10 | + |
| 11 | +export const GET = defineInternalJsonRoute({ |
| 12 | + contract: listOAuthConnectionsContract, |
| 13 | + auth: internalSessionAuth, |
| 14 | + operation: credentialUserOperations.listOAuthConnections, |
| 15 | + rateLimit: internalRateLimits.none({ reason: 'Preserve existing internal behavior' }), |
| 16 | + errorPolicy: internalCredentialErrorPolicy, |
| 17 | + mapInput: () => ({}), |
| 18 | + useCase: listOAuthConnectionsUseCase, |
139 | 19 | }) |
0 commit comments