diff --git a/src/app/api/v1/auth/api-keys/route.ts b/src/app/api/v1/auth/api-keys/route.ts index b4700a2..e517c33 100644 --- a/src/app/api/v1/auth/api-keys/route.ts +++ b/src/app/api/v1/auth/api-keys/route.ts @@ -1,5 +1,5 @@ import { NextRequest, NextResponse } from 'next/server' -import { createServerClient } from '@/lib/supabase' +import { createServerClient, createSSRClient } from '@/lib/supabase' import bcrypt from 'bcryptjs' import crypto from 'crypto' @@ -12,6 +12,13 @@ async function getAuthContext(req: NextRequest) { const walletAddress = getWalletAddress(req) if (!walletAddress) return null + const supabaseSsr = await createSSRClient() + const { data: { user } } = await supabaseSsr.auth.getUser() + + if (!user || user.user_metadata?.wallet_address !== walletAddress) { + return null + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any const supabase = createServerClient() as any return { supabase, walletAddress } diff --git a/src/lib/supabase.ts b/src/lib/supabase.ts index 9f907d8..c2d49d2 100644 --- a/src/lib/supabase.ts +++ b/src/lib/supabase.ts @@ -1,6 +1,7 @@ -import { createBrowserClient } from '@supabase/ssr' +import { createBrowserClient, createServerClient as createSupabaseSSRClient } from '@supabase/ssr' import { createClient as createSupabaseClient, SupabaseClient } from '@supabase/supabase-js' import { Database } from '@/types/database.types' +import { cookies } from 'next/headers' // Client-side (Browser) export const createClient = () => @@ -9,9 +10,33 @@ export const createClient = () => process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY! ) +// Server-side (SSR with cookies) +export const createSSRClient = async () => { + const cookieStore = await cookies() + return createSupabaseSSRClient( + 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: any) { + try { cookieStore.set({ name, value, ...options }) } catch (error) {} + }, + remove(name: string, options: any) { + try { cookieStore.delete({ name, ...options }) } catch (error) {} + }, + }, + } + ) +} + // Server-side (API Routes, Services, Background Jobs) export const createServerClient = () => createSupabaseClient( process.env.NEXT_PUBLIC_SUPABASE_URL!, process.env.SUPABASE_SERVICE_ROLE_KEY || process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY! ) as SupabaseClient + +export const createAdminClient = createServerClient