// 切换用户下载权限API import { NextRequest, NextResponse } from 'next/server'; import { getServerSession } from 'next-auth'; import { authOptions } from '@/lib/auth'; import { prisma } from '@/lib/prisma'; import { isSystemAdmin } from '@/lib/department-permission'; // POST - 切换用户下载权限(仅管理员) export async function POST(request: NextRequest) { try { const session = await getServerSession(authOptions); if (!session?.user || !(session.user as any).id) { return NextResponse.json( { error: '未登录' }, { status: 401 } ); } const userRole = (session.user as any).role; if (!isSystemAdmin(userRole)) { return NextResponse.json( { error: '无权限' }, { status: 403 } ); } const { userId } = await request.json(); if (!userId) { return NextResponse.json( { error: '缺少用户ID' }, { status: 400 } ); } const sessionUserId = (session.user as any).id; // 不能修改自己的下载权限 if (userId === sessionUserId) { return NextResponse.json( { error: '不能修改自己的下载权限' }, { status: 400 } ); } // 检查用户是否存在 const user = await prisma.user.findUnique({ where: { id: userId }, }); if (!user) { return NextResponse.json( { error: '用户不存在' }, { status: 404 } ); } // 不能修改管理员的下载权限 if (user.role === 'ADMIN') { return NextResponse.json( { error: '不能修改管理员的下载权限' }, { status: 400 } ); } // 切换下载权限 const updatedUser = await prisma.user.update({ where: { id: userId }, data: { canDownload: !user.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 } ); } }