/** * Edge Function: list-users * Propósito: devuelve usuarios de public.users con email de auth.users (requiere service_role). * Solo accesible por platform_admin. * Deploy: supabase functions deploy list-users */ import { createClient } from 'https://esm.sh/@supabase/supabase-js@2' Deno.serve(async (req: Request) => { const headers = { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'POST, GET, OPTIONS', 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type', } if (req.method === 'OPTIONS') { return new Response('ok', { headers }) } const adminClient = createClient( Deno.env.get('SUPABASE_URL')!, Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!, ) // ── 1. Autenticar al llamador ────────────────────────────────────────────── const callerToken = req.headers.get('Authorization')?.replace('Bearer ', '') if (!callerToken) { return new Response(JSON.stringify({ error: 'Authorization header requerido' }), { status: 401, headers }) } const { data: { user: caller }, error: authError } = await adminClient.auth.getUser(callerToken) if (authError || !caller) { return new Response(JSON.stringify({ error: 'Token inválido o expirado' }), { status: 401, headers }) } const { data: callerProfile, error: profileError } = await adminClient .from('users') .select('platform_role') .eq('id', caller.id) .single() if (profileError || callerProfile?.platform_role !== 'platform_admin') { return new Response( JSON.stringify({ error: 'Forbidden: solo platform_admin puede listar usuarios con email' }), { status: 403, headers }, ) } // ── 2. Obtener emails de auth.users ─────────────────────────────────────── const { data: authData, error: listError } = await adminClient.auth.admin.listUsers({ page: 1, perPage: 1000, }) if (listError) { return new Response( JSON.stringify({ error: `Error al listar usuarios: ${listError.message}` }), { status: 500, headers }, ) } // ── 3. Devolver mapa id → email ─────────────────────────────────────────── const result = (authData?.users ?? []).map((u) => ({ id: u.id, email: u.email ?? null, })) return new Response(JSON.stringify(result), { status: 200, headers }) })