66 lines
2.4 KiB
TypeScript
66 lines
2.4 KiB
TypeScript
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 })
|
||
}
|
||
}
|
||
|
||
|