VidSimplify / frontend /src /app /api /auth /sync /route.ts
Adityahulk
Restoring repo state for deployment
6fc3143
Raw
History Blame Contribute Delete
3.57 kB
import { createServerClient, type CookieOptions } from '@supabase/ssr'
import { cookies } from 'next/headers'
import { NextResponse } from 'next/server'
export async function POST() {
console.log("\nπŸ”„ === SYNC API CALLED ===");
const cookieStore = cookies()
// Debug: Log all cookies to see if auth token is present
const allCookies = cookieStore.getAll().map(c => c.name);
console.log("Cookies received:", allCookies);
// Create authenticated Supabase client
const supabase = createServerClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
{
cookies: {
get(name: string) {
return cookieStore.get(name)?.value
},
set(name: string, value: string, options: CookieOptions) {
try {
cookieStore.set({ name, value, ...options })
} catch (error) {
// Route handlers can't set cookies in some Next.js versions/contexts,
// but we only need to READ them for auth here.
}
},
remove(name: string, options: CookieOptions) {
try {
cookieStore.delete({ name, ...options })
} catch (error) {
// Ignore
}
},
},
}
)
// Get current user
console.log("Getting current user...");
const { data: { user }, error: authError } = await supabase.auth.getUser()
if (authError || !user) {
console.error("❌ Not authenticated:", authError?.message);
return NextResponse.json({ error: 'Not authenticated', details: authError?.message }, { status: 401 })
}
console.log("βœ… User authenticated:", user.id);
try {
// Check if user exists
console.log("Checking if user exists in DB...");
const { data: existingUser, error: fetchError } = await supabase
.from('users')
.select('id')
.eq('id', user.id)
.single()
console.log("Fetch result:", { existingUser, fetchError });
if (!existingUser) {
console.log(`πŸ”„ User ${user.id} not found. Inserting...`)
const insertData = {
id: user.id,
email: user.email,
full_name: user.user_metadata.full_name || null,
avatar_url: user.user_metadata.avatar_url || null,
credits: 5
};
console.log("Insert data:", insertData);
// Insert user using the AUTHENTICATED client (acting as the user)
const { data: insertResult, error: insertError } = await supabase
.from('users')
.insert(insertData)
.select()
if (insertError) {
console.error('❌ Sync insert error:', insertError)
return NextResponse.json({ error: insertError.message }, { status: 500 })
}
console.log("βœ… User created successfully:", insertResult);
return NextResponse.json({ status: 'created', user: insertResult })
}
console.log("βœ… User already exists");
return NextResponse.json({ status: 'exists' })
} catch (err) {
console.error('❌ Sync error:', err)
return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 })
}
}