55 lines
2.0 KiB
TypeScript

/* eslint-disable @typescript-eslint/no-explicit-any */
import { NextResponse } from 'next/server'
import { createClient } from '@/lib/supabase/server'
import { createAdminClient } from '@/lib/supabase/server'
async function assertAdmin() {
const supabase = await createClient()
const db = supabase as any
const { data: { user }, error } = await supabase.auth.getUser()
if (error || !user) return null
const { data: profile } = await db.from('profiles').select('role').eq('id', user.id).single()
if (profile?.role !== 'admin') return null
return user
}
export async function GET() {
try {
const caller = await assertAdmin()
if (!caller) return NextResponse.json({ error: 'Accès refusé' }, { status: 403 })
const admin = createAdminClient()
const adminDb = admin as any
// Récupérer tous les utilisateurs via la fonction SECURITY DEFINER
const { data: authUsers, error: authError } = await adminDb.rpc('get_all_users_admin')
if (authError) return NextResponse.json({ error: authError.message }, { status: 500 })
// Récupérer tous les profils
const { data: profiles, error: profilesError } = await adminDb
.from('profiles')
.select('id, username, role, created_at')
.order('created_at', { ascending: false })
if (profilesError) return NextResponse.json({ error: profilesError.message }, { status: 500 })
// Merger par user ID
const profileMap = new Map((profiles ?? []).map((p: any) => [p.id, p]))
const users = (authUsers ?? []).map((authUser: any) => {
const profile: any = profileMap.get(authUser.id) ?? {}
return {
id: authUser.id,
email: authUser.email,
username: profile.username ?? authUser.email?.split('@')[0] ?? '—',
role: profile.role ?? 'formateur',
created_at: profile.created_at ?? authUser.created_at,
last_sign_in: authUser.last_sign_in_at ?? null,
}
})
return NextResponse.json({ users })
} catch {
return NextResponse.json({ error: 'Erreur serveur' }, { status: 500 })
}
}