39 lines
2.6 KiB
TypeScript
39 lines
2.6 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'
|
|
import type { AiModelDatabase } from './ai-model-repository'
|
|
|
|
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.isActive || (user.status || 'active') !== 'active' || user.archivedAt) throw new AiModelError('账号当前不可用', 403, 'account_inactive')
|
|
return userId
|
|
}
|
|
|
|
export async function assertAiModelAdminForWrite(userId: string, db: AiModelDatabase): Promise<void> {
|
|
const rows = await db.$queryRawUnsafe<Array<{ isSuperAdmin: boolean; isActive: boolean; status: string | null; archivedAt: Date | null }>>('SELECT "isSuperAdmin","isActive",status,"archivedAt" FROM users WHERE id=$1 FOR SHARE', userId)
|
|
const user = rows[0]
|
|
if (!user?.isSuperAdmin) throw new AiModelError('仅超级管理员可管理 AI 模型', 403, 'forbidden')
|
|
if (!user.isActive || (user.status || 'active') !== 'active' || user.archivedAt) throw new AiModelError('账号当前不可用', 403, 'account_inactive')
|
|
}
|
|
|
|
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' } })
|
|
}
|
|
}
|