80 lines
2.8 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import { isSuperAdmin } from '@/lib/department-permission'
import { AutoListingCallbackError } from '@/lib/external-auto-listing-callback'
import {
buildExternalNotificationTargetAdminView,
createExternalNotificationTarget,
listExternalNotificationTargets,
} from '@/lib/external-auto-listing'
async function assertAdminPermission() {
const session = await getServerSession(authOptions)
if (!session?.user || !(session.user as any).id) {
return NextResponse.json({ success: false, error: '未登录' }, { status: 401 })
}
const userId = (session.user as any).id
if (!(await isSuperAdmin(userId))) {
return NextResponse.json({ success: false, error: '仅超级管理员可访问' }, { status: 403 })
}
return null
}
function toErrorResponse(error: unknown) {
return error instanceof AutoListingCallbackError
? NextResponse.json({ success: false, error: error.message }, { status: error.status })
: NextResponse.json({ success: false, error: '服务器错误' }, { status: 500 })
}
export async function GET(request: NextRequest) {
try {
const authError = await assertAdminPermission()
if (authError) {
return authError
}
const targets = await listExternalNotificationTargets()
return NextResponse.json({
success: true,
data: targets.map(buildExternalNotificationTargetAdminView),
})
} catch (error) {
console.error('[admin/external-notification-targets] GET error:', error instanceof Error ? error.name : 'UnknownError')
return toErrorResponse(error)
}
}
export async function POST(request: NextRequest) {
try {
const authError = await assertAdminPermission()
if (authError) {
return authError
}
const body = await request.json()
const target = await createExternalNotificationTarget({
name: typeof body?.name === 'string' ? body.name : '',
callbackUrl: typeof body?.callbackUrl === 'string' ? body.callbackUrl : '',
authType: typeof body?.authType === 'string' ? body.authType : undefined,
authConfig:
body?.authConfig && typeof body.authConfig === 'object' && !Array.isArray(body.authConfig)
? body.authConfig
: undefined,
eventTypes: Array.isArray(body?.eventTypes) ? body.eventTypes : undefined,
isActive: typeof body?.isActive === 'boolean' ? body.isActive : undefined,
})
return NextResponse.json({
success: true,
data: buildExternalNotificationTargetAdminView(target),
message: '通知目标创建成功',
})
} catch (error) {
console.error('[admin/external-notification-targets] POST error:', error instanceof Error ? error.name : 'UnknownError')
return toErrorResponse(error)
}
}