2026-05-28 23:27:15 +08:00

102 lines
2.6 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import { prisma } from '@/lib/prisma'
import { isCurrentSuperAdmin } from '@/lib/admin-permissions'
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 }
)
}
if (!(await isCurrentSuperAdmin(session))) {
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 },
select: { id: true, email: true, department: true }
})
if (!targetUser) {
return NextResponse.json(
{ error: '用户不存在' },
{ status: 404 }
)
}
// 获取目标用户的完整信息(包括 isSuperAdmin)
const targetUserFull = await prisma.user.findUnique({
where: { id: userId },
}) as any
// 不能修改自己的角色
if (targetUser.email === session.user?.email) {
return NextResponse.json(
{ error: '不能修改自己的角色' },
{ status: 400 }
)
}
// 最高权限账号不能被修改角色
if (targetUserFull?.isSuperAdmin) {
return NextResponse.json(
{ error: '不能修改最高权限账号的角色' },
{ status: 400 }
)
}
// 更新用户角色
const updatedUser = await prisma.user.update({
where: { id: userId },
data: role === 'USER'
? { role, managedDepartment: null }
: { 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 }
)
}
}