gongxiangp2/lib/ai-model-access.ts

31 lines
1.9 KiB
TypeScript

import { getServerSession } from 'next-auth'
import { NextResponse } from 'next/server'
import { authOptions } from '@/lib/auth'
import { isSuperAdmin } from '@/lib/department-permission'
import { prisma } from '@/lib/prisma'
import { DetailGeneratorError } from '@/lib/detail-generator/access'
export class AiModelError extends DetailGeneratorError {
constructor(message: string, status = 400, code = 'invalid_request') { super(message, status, code); this.name = 'AiModelError' }
}
export async function assertAiModelAdmin(userId: string | null | undefined): Promise<string> {
if (!userId) throw new AiModelError('请先登录', 401, 'unauthenticated')
if (!(await isSuperAdmin(userId))) throw new AiModelError('仅超级管理员可管理 AI 模型', 403, 'forbidden')
const user = await prisma.user.findUnique({ where: { id: userId }, select: { isSuperAdmin: true, status: true, isActive: true, archivedAt: true } })
if (!user?.isSuperAdmin) throw new AiModelError('仅超级管理员可管理 AI 模型', 403, 'forbidden')
if ((user.status || (user.isActive ? 'active' : 'pending')) !== 'active' || user.archivedAt) throw new AiModelError('账号当前不可用', 403, 'account_inactive')
return userId
}
export async function aiModelAdminRoute(action: (userId: string) => Promise<unknown>): Promise<NextResponse> {
try {
const session = await getServerSession(authOptions)
const userId = await assertAiModelAdmin((session?.user as { id?: string } | undefined)?.id)
return NextResponse.json(await action(userId), { headers: { 'Cache-Control': 'private, no-store' } })
} catch (error) {
const known = error instanceof AiModelError || error instanceof DetailGeneratorError
return NextResponse.json({ error: known ? error.message : 'AI 模型操作暂未完成,请稍后重试', code: known ? error.code : 'internal_error' }, { status: known ? error.status : 500, headers: { 'Cache-Control': 'private, no-store' } })
}
}