79 lines
1.8 KiB
TypeScript
79 lines
1.8 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server'
|
|
import { getServerSession } from 'next-auth'
|
|
import { authOptions } from '@/lib/auth'
|
|
import { prisma } from '@/lib/prisma'
|
|
|
|
export async function POST(req: NextRequest) {
|
|
try {
|
|
const session = await getServerSession(authOptions)
|
|
|
|
// 检查是否为管理员
|
|
if (!session || (session.user as any)?.role !== 'ADMIN') {
|
|
return NextResponse.json(
|
|
{ error: '权限不足' },
|
|
{ status: 403 }
|
|
)
|
|
}
|
|
|
|
const { userId, role } = await req.json()
|
|
|
|
if (!userId || !role) {
|
|
return NextResponse.json(
|
|
{ error: '参数错误' },
|
|
{ status: 400 }
|
|
)
|
|
}
|
|
|
|
// 验证角色值
|
|
if (role !== 'USER' && role !== 'ADMIN') {
|
|
return NextResponse.json(
|
|
{ error: '角色值无效' },
|
|
{ status: 400 }
|
|
)
|
|
}
|
|
|
|
// 检查目标用户是否存在
|
|
const targetUser = await prisma.user.findUnique({
|
|
where: { id: userId },
|
|
})
|
|
|
|
if (!targetUser) {
|
|
return NextResponse.json(
|
|
{ error: '用户不存在' },
|
|
{ status: 404 }
|
|
)
|
|
}
|
|
|
|
// 不能修改自己的角色
|
|
if (targetUser.email === session.user?.email) {
|
|
return NextResponse.json(
|
|
{ error: '不能修改自己的角色' },
|
|
{ status: 400 }
|
|
)
|
|
}
|
|
|
|
// 更新用户角色
|
|
const updatedUser = await prisma.user.update({
|
|
where: { id: userId },
|
|
data: { role },
|
|
})
|
|
|
|
return NextResponse.json({
|
|
success: true,
|
|
user: {
|
|
id: updatedUser.id,
|
|
email: updatedUser.email,
|
|
username: updatedUser.username,
|
|
role: updatedUser.role,
|
|
},
|
|
})
|
|
} catch (error) {
|
|
console.error('Error updating user role:', error)
|
|
return NextResponse.json(
|
|
{ error: '设置角色失败' },
|
|
{ status: 500 }
|
|
)
|
|
}
|
|
}
|
|
|