File size: 2,972 Bytes
c7fbc2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import { NextResponse, NextRequest } from 'next/server'
import { createServerClient } from '@supabase/ssr'
import { prisma } from '@/lib/prisma'

export async function GET(request: NextRequest) {
    const { searchParams, origin } = new URL(request.url)
    const code = searchParams.get('code')
    // if "next" is in param, use it as the redirect URL
    const next = searchParams.get('next') ?? '/dashboard'

    // Determine the correct redirect origin (handling ngrok)
    const forwardedHost = request.headers.get('x-forwarded-host')
    let redirectOrigin = origin;

    // If behind ngrok/proxy, use that host
    if (forwardedHost) {
        redirectOrigin = `https://${forwardedHost}`
    } else if (process.env.NODE_ENV === 'development') {
        // Force HTTP for localhost to avoid SSL errors if not using ngrok
        redirectOrigin = origin.replace('https', 'http')
    }

    if (code) {
        // Create a response object first so we can manipulate its cookies
        const response = NextResponse.redirect(`${redirectOrigin}${next}`)

        const supabase = createServerClient(
            process.env.NEXT_PUBLIC_SUPABASE_URL!,
            process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
            {
                cookies: {
                    getAll() {
                        return request.cookies.getAll() as any; // Cast to any if needed to match generic type
                    },
                    setAll(cookiesToSet) {
                        cookiesToSet.forEach(({ name, value, options }) =>
                            request.cookies.set(name, value)
                        )
                        cookiesToSet.forEach(({ name, value, options }) =>
                            response.cookies.set(name, value, options)
                        )
                    },
                },
            }
        )

        const { error, data: { session } } = await supabase.auth.exchangeCodeForSession(code)

        if (!error && session?.user) {
            // Sync user to Prisma
            try {
                const { user } = session;
                const email = user.email!;
                if (email) {
                    await prisma.user.upsert({
                        where: { email },
                        update: {
                            image: user.user_metadata?.avatar_url || user.user_metadata?.picture
                        },
                        create: {
                            id: user.id,
                            email,
                            image: user.user_metadata?.avatar_url || user.user_metadata?.picture,
                        }
                    });
                }
            } catch (e) {
                console.error("Failed to sync user to Prisma:", e)
            }

            return response
        }
    }

    // return the user to an error page with instructions
    return NextResponse.redirect(`${redirectOrigin}/auth/auth-code-error`)
}