WuYongJie f646b71813
Some checks failed
CI Check / check (push) Has been cancelled
chore: 初始化本地仓库并同步最近改动
2025-11-18 17:50:16 +08:00

119 lines
3.0 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'
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 currentUser = await prisma.user.findUnique({
where: { id: (session.user as any).id },
select: { id: true, email: true, managedDepartment: true }
})
if (!currentUser) {
return NextResponse.json(
{ error: '当前用户不存在' },
{ status: 404 }
)
}
// 获取当前用户的完整信息(包括 isSuperAdmin)
const currentUserFull = await prisma.user.findUnique({
where: { id: (session.user as any).id },
}) as any
// 检查目标用户是否存在
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 (!currentUserFull?.isSuperAdmin) {
return NextResponse.json(
{ error: '权限不足:只有最高权限账号可以修改用户角色' },
{ status: 403 }
)
}
// 最高权限账号不能被修改角色
if (targetUserFull?.isSuperAdmin) {
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 }
)
}
}