|
| 1 | +import { createLogger } from '@sim/logger' |
| 2 | +import { type NextRequest, NextResponse } from 'next/server' |
| 3 | +import { authorizeOAuth2Contract } from '@/lib/api/contracts/oauth-connections' |
| 4 | +import { parseRequest } from '@/lib/api/server' |
| 5 | +import { auth, getSession } from '@/lib/auth/auth' |
| 6 | +import { getBaseUrl } from '@/lib/core/utils/urls' |
| 7 | +import { withRouteHandler } from '@/lib/core/utils/with-route-handler' |
| 8 | + |
| 9 | +const logger = createLogger('OAuth2Authorize') |
| 10 | + |
| 11 | +export const dynamic = 'force-dynamic' |
| 12 | + |
| 13 | +/** |
| 14 | + * Browser-initiated entrypoint for linking a generic OAuth2 account. |
| 15 | + */ |
| 16 | +export const GET = withRouteHandler(async (request: NextRequest) => { |
| 17 | + const baseUrl = getBaseUrl() |
| 18 | + |
| 19 | + const session = await getSession() |
| 20 | + if (!session?.user?.id) { |
| 21 | + const loginUrl = new URL('/login', baseUrl) |
| 22 | + loginUrl.searchParams.set('callbackUrl', request.nextUrl.pathname + request.nextUrl.search) |
| 23 | + return NextResponse.redirect(loginUrl.toString()) |
| 24 | + } |
| 25 | + |
| 26 | + const parsed = await parseRequest(authorizeOAuth2Contract, request, {}) |
| 27 | + if (!parsed.success) return parsed.response |
| 28 | + const { providerId, callbackURL: requestedCallback } = parsed.data.query |
| 29 | + |
| 30 | + const callbackURL = requestedCallback?.startsWith(`${baseUrl}/`) |
| 31 | + ? requestedCallback |
| 32 | + : `${baseUrl}/workspace` |
| 33 | + |
| 34 | + try { |
| 35 | + const linkResponse = await auth.api.oAuth2LinkAccount({ |
| 36 | + body: { providerId, callbackURL }, |
| 37 | + headers: request.headers, |
| 38 | + asResponse: true, |
| 39 | + }) |
| 40 | + |
| 41 | + const payload = (await linkResponse.json().catch(() => null)) as { url?: string } | null |
| 42 | + if (!linkResponse.ok || !payload?.url) { |
| 43 | + logger.error('oAuth2LinkAccount did not return an authorization URL', { |
| 44 | + providerId, |
| 45 | + status: linkResponse.status, |
| 46 | + }) |
| 47 | + return NextResponse.redirect(`${baseUrl}/workspace?error=oauth_link_failed`) |
| 48 | + } |
| 49 | + |
| 50 | + const response = NextResponse.redirect(payload.url) |
| 51 | + // Forward the signed `state` cookie Better Auth set so it lands in the user's |
| 52 | + // browser and is present when the provider redirects back to the callback. |
| 53 | + const linkHeaders = linkResponse.headers as Headers & { |
| 54 | + getSetCookie?: () => string[] |
| 55 | + } |
| 56 | + for (const cookie of linkHeaders.getSetCookie?.() ?? []) { |
| 57 | + response.headers.append('set-cookie', cookie) |
| 58 | + } |
| 59 | + return response |
| 60 | + } catch (error) { |
| 61 | + logger.error('Failed to initiate OAuth2 authorization', { providerId, error }) |
| 62 | + return NextResponse.redirect(`${baseUrl}/workspace?error=oauth_link_failed`) |
| 63 | + } |
| 64 | +}) |
0 commit comments