| import { createServerClient } from "@supabase/ssr"; |
| import { cookies } from "next/headers"; |
| import { NextResponse } from "next/server"; |
|
|
| import { getSupabaseAdmin } from "@/lib/supabase/admin"; |
|
|
| async function checkAdminAccess(supabase: ReturnType<typeof createServerClient>) { |
| const { data: { user } } = await supabase.auth.getUser(); |
| if (!user) return false; |
|
|
| const { data: member } = await supabase |
| .from("members") |
| .select("is_superuser") |
| .eq("user_id", user.id) |
| .single(); |
|
|
| return member?.is_superuser === true; |
| } |
|
|
| export async function GET() { |
| const cookieStore = await cookies(); |
| |
| const supabaseAuth = createServerClient( |
| process.env.NEXT_PUBLIC_SUPABASE_URL!, |
| process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!, |
| { |
| cookies: { |
| getAll() { |
| return cookieStore.getAll(); |
| }, |
| setAll() {}, |
| }, |
| } |
| ); |
|
|
| const isAdmin = await checkAdminAccess(supabaseAuth); |
| if (!isAdmin) { |
| return NextResponse.json({ ok: false, error: "Forbidden" }, { status: 403 }); |
| } |
|
|
| try { |
| const supabaseAdmin = getSupabaseAdmin(); |
| |
| const { data: authData } = await supabaseAdmin.auth.admin.listUsers(); |
| const authUsers = authData?.users ?? []; |
|
|
| |
| const { data: members } = await supabaseAdmin |
| .from("members") |
| .select("user_id, is_superuser, organization_id, organizations!inner(id, name, slug)") |
| .order("created_at", { ascending: false }); |
|
|
| |
| const users = authUsers.map((authUser) => { |
| const member = members?.find((m) => m.user_id === authUser.id); |
| const org = member?.organizations?.[0]; |
| return { |
| userId: authUser.id, |
| email: authUser.email ?? "Unknown", |
| orgName: org?.name ?? "No Organization", |
| orgSlug: org?.slug ?? "none", |
| isSuperuser: member?.is_superuser ?? false, |
| createdAt: authUser.created_at, |
| lastSignIn: authUser.last_sign_in_at, |
| }; |
| }); |
|
|
| return NextResponse.json({ ok: true, data: { users } }); |
| } catch (error) { |
| return NextResponse.json( |
| { ok: false, error: "Failed to fetch users" }, |
| { status: 500 } |
| ); |
| } |
| } |
|
|