|
1 | 1 | import { randomUUID } from 'node:crypto'; |
2 | | -import { account, and, db, eq, user } from '@databuddy/db'; |
| 2 | +import { auth } from '@databuddy/auth'; |
| 3 | +import { account, and, db, eq } from '@databuddy/db'; |
| 4 | +import { headers } from 'next/headers'; |
3 | 5 | import { type NextRequest, NextResponse } from 'next/server'; |
4 | 6 |
|
5 | 7 | interface VercelTokenResponse { |
@@ -29,6 +31,19 @@ export async function GET(request: NextRequest) { |
29 | 31 | ); |
30 | 32 | } |
31 | 33 |
|
| 34 | + // Check if user is authenticated |
| 35 | + const session = await auth.api.getSession({ headers: await headers() }); |
| 36 | + |
| 37 | + // If no session, redirect to auth pages with the callback URL |
| 38 | + if (!session?.user) { |
| 39 | + const callbackUrl = new URL(request.url); |
| 40 | + const completeIntegrationUrl = `${process.env.BETTER_AUTH_URL}${callbackUrl.pathname}${callbackUrl.search}`; |
| 41 | + |
| 42 | + return NextResponse.redirect( |
| 43 | + `${process.env.BETTER_AUTH_URL}/register?callback=${encodeURIComponent(completeIntegrationUrl)}` |
| 44 | + ); |
| 45 | + } |
| 46 | + |
32 | 47 | const redirectUri = `${process.env.BETTER_AUTH_URL}/api/integrations/vercel/callback`; |
33 | 48 |
|
34 | 49 | const tokenResponse = await fetch( |
@@ -76,21 +91,7 @@ export async function GET(request: NextRequest) { |
76 | 91 | ); |
77 | 92 | } |
78 | 93 |
|
79 | | - const existingUser = await db.query.user.findFirst({ |
80 | | - where: eq(user.email, userInfo.email), |
81 | | - }); |
82 | | - |
83 | | - if (!existingUser) { |
84 | | - // Create the callback URL that will complete the integration after auth |
85 | | - const callbackUrl = new URL(request.url); |
86 | | - const completeIntegrationUrl = `${process.env.BETTER_AUTH_URL}${callbackUrl.pathname}${callbackUrl.search}`; |
87 | | - |
88 | | - return NextResponse.redirect( |
89 | | - `${process.env.BETTER_AUTH_URL}/register?email=${encodeURIComponent(userInfo.email)}&name=${encodeURIComponent(userInfo.name || '')}&callback=${encodeURIComponent(completeIntegrationUrl)}` |
90 | | - ); |
91 | | - } |
92 | | - |
93 | | - const userId = existingUser.id; |
| 94 | + const userId = session.user.id; |
94 | 95 |
|
95 | 96 | const existingAccount = await db.query.account.findFirst({ |
96 | 97 | where: and(eq(account.userId, userId), eq(account.providerId, 'vercel')), |
|
0 commit comments