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

66 lines
2.4 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 bcrypt from 'bcryptjs'
export async function POST(req: NextRequest) {
try {
const session = await getServerSession(authOptions)
if (!session) {
return NextResponse.json({ error: '未登录' }, { status: 401 })
}
const requesterId = (session.user as any)?.id
const requester = await prisma.user.findUnique({ where: { id: requesterId } }) as any
if (!requester || !requester.isSuperAdmin) {
return NextResponse.json({ error: '仅最高权限账号可转移最高权限' }, { status: 403 })
}
const body = await req.json()
const targetUserId: string | undefined = body?.targetUserId
const targetEmail: string | undefined = body?.targetEmail
const password: string | undefined = body?.password
// 验证密码
if (!password) {
return NextResponse.json({ error: '请输入密码以确认操作' }, { status: 400 })
}
const isPasswordValid = await bcrypt.compare(password, requester.password)
if (!isPasswordValid) {
return NextResponse.json({ error: '密码错误' }, { status: 400 })
}
if (!targetUserId && !targetEmail) {
return NextResponse.json({ error: '缺少目标用户标识(targetUserId 或 targetEmail)' }, { status: 400 })
}
if (targetUserId && targetUserId === requesterId) {
return NextResponse.json({ error: '不能转移给自己' }, { status: 400 })
}
const targetUser = targetUserId
? await prisma.user.findUnique({ where: { id: targetUserId } })
: await prisma.user.findUnique({ where: { email: targetEmail! } })
if (!targetUser) {
return NextResponse.json({ error: '目标用户不存在' }, { status: 404 })
}
if (targetUser.id === requesterId) {
return NextResponse.json({ error: '不能转移给自己' }, { status: 400 })
}
// 事务:转移最高权限
await prisma.$transaction([
prisma.user.update({ where: { id: requesterId }, data: { isSuperAdmin: false } as any }),
prisma.user.update({ where: { id: targetUser.id }, data: { isSuperAdmin: true } as any }),
])
return NextResponse.json({ message: '最高权限已转移' })
} catch (error) {
console.error('Transfer super admin error:', error)
return NextResponse.json({ error: '操作失败' }, { status: 500 })
}
}