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

128 lines
3.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 { buildDepartmentDescendants, isDepartmentWithinScope } from '@/lib/departments'
// Toggle user download permission (admin only)
export async function POST(req: NextRequest) {
try {
const session = await getServerSession(authOptions)
// Check if user is admin
if (!session || (session.user as any).role !== 'ADMIN') {
return NextResponse.json(
{ error: '无权限' },
{ status: 403 }
)
}
const { userId } = await req.json()
if (!userId) {
return NextResponse.json(
{ error: '缺少用户ID' },
{ status: 400 }
)
}
// Prevent admin from disabling their own download permission
if (userId === (session.user as any).id) {
return NextResponse.json(
{ error: '不能修改自己的下载权限' },
{ status: 400 }
)
}
const currentUser = await prisma.user.findUnique({
where: { id: (session.user as any).id },
select: { id: true, managedDepartment: true, isSuperAdmin: true },
})
if (!currentUser) {
return NextResponse.json(
{ error: '当前用户不存在' },
{ status: 404 }
)
}
let departmentDescendantsMap: Map<string, Set<string>> | undefined
if (currentUser.managedDepartment && !currentUser.isSuperAdmin) {
const departments = await prisma.department.findMany({ select: { name: true } })
departmentDescendantsMap = buildDepartmentDescendants(departments)
}
// Get target user
const targetUser = await prisma.user.findUnique({
where: { id: userId },
select: {
id: true,
department: true,
role: true,
canDownload: true,
isSuperAdmin: true,
},
})
if (!targetUser) {
return NextResponse.json(
{ error: '用户不存在' },
{ status: 404 }
)
}
// Prevent disabling download for other admins
if (targetUser.role === 'ADMIN') {
return NextResponse.json(
{ error: '不能修改管理员的下载权限' },
{ status: 400 }
)
}
if (targetUser.isSuperAdmin && !currentUser.isSuperAdmin) {
return NextResponse.json(
{ error: '不能修改最高权限账号的下载权限' },
{ status: 403 }
)
}
if (!currentUser.isSuperAdmin) {
if (!currentUser.managedDepartment) {
return NextResponse.json(
{ error: '权限不足:未被授权管理任何分支' },
{ status: 403 }
)
}
const allowed = isDepartmentWithinScope(
currentUser.managedDepartment,
targetUser.department,
departmentDescendantsMap
)
if (!allowed) {
return NextResponse.json(
{ error: '权限不足:只能管理自己部门树范围内的用户下载权限' },
{ status: 403 }
)
}
}
// Toggle download permission
const updatedUser = await prisma.user.update({
where: { id: userId },
data: { canDownload: !targetUser.canDownload },
})
return NextResponse.json({
message: updatedUser.canDownload ? '已开启下载权限' : '已关闭下载权限',
canDownload: updatedUser.canDownload,
})
} catch (error) {
console.error('Error toggling download permission:', error)
return NextResponse.json(
{ error: '操作失败' },
{ status: 500 }
)
}
}