2025-10-26 09:11:04 +08:00

75 lines
1.9 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import { prisma } from '@/lib/prisma'
// 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 }
)
}
// Get current user
const user = await prisma.user.findUnique({
where: { id: userId },
})
if (!user) {
return NextResponse.json(
{ error: '用户不存在' },
{ status: 404 }
)
}
// Prevent disabling download for other admins
if (user.role === 'ADMIN') {
return NextResponse.json(
{ error: '不能修改管理员的下载权限' },
{ status: 400 }
)
}
// Toggle download permission
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 }
)
}
}