43 lines
1.5 KiB
TypeScript
43 lines
1.5 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server'
|
|
import { getServerSession } from 'next-auth'
|
|
import { authOptions } from '@/lib/auth'
|
|
import { prisma } from '@/lib/prisma'
|
|
import bcrypt from 'bcryptjs'
|
|
|
|
async function requireAdmin() {
|
|
const session = await getServerSession(authOptions)
|
|
if (!session || session.user.role !== 'admin') return null
|
|
return session
|
|
}
|
|
|
|
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
export async function GET(_req: NextRequest) {
|
|
const session = await requireAdmin()
|
|
if (!session) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
|
|
|
const users = await prisma.user.findMany({
|
|
orderBy: { createdAt: 'asc' },
|
|
select: { id: true, email: true, name: true, role: true, createdAt: true },
|
|
})
|
|
return NextResponse.json(users)
|
|
}
|
|
|
|
export async function POST(req: NextRequest) {
|
|
const session = await requireAdmin()
|
|
if (!session) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
|
|
|
const body = await req.json().catch(() => ({}))
|
|
const { email, name, password, role } = body as Record<string, string>
|
|
|
|
if (!email || !name || !password || !role) {
|
|
return NextResponse.json({ error: 'email, name, password et role requis' }, { status: 400 })
|
|
}
|
|
|
|
const hashed = await bcrypt.hash(password, 12)
|
|
const user = await prisma.user.create({
|
|
data: { email, name, password: hashed, role },
|
|
select: { id: true, email: true, name: true, role: true, createdAt: true },
|
|
})
|
|
return NextResponse.json(user, { status: 201 })
|
|
}
|