2026-06-02 10:16:28 +08:00

112 lines
3.2 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 { uploadToS3 } from '@/lib/s3'
import { isCurrentSuperAdmin } from '@/lib/admin-permissions'
import { processImage } from '@/lib/image-processor'
import { canUseSystemSettings } from '@/lib/license'
// POST - 上传LOGO(最高权限)
export async function POST(request: NextRequest) {
try {
const session = await getServerSession(authOptions)
if (!session || !(await isCurrentSuperAdmin(session))) {
return NextResponse.json(
{ error: '只有最高权限账号可以修改系统LOGO' },
{ status: 403 }
)
}
if (!(await canUseSystemSettings())) {
return NextResponse.json(
{ error: '当前许可证未包含系统设置功能,请联系管理员处理授权' },
{ status: 403 }
)
}
// 将NextRequest转换为Node.js IncomingMessage
const formData = await request.formData()
const logoFile = formData.get('logo') as File
const logoType = formData.get('type') as string // 'header' or 'login'
if (!logoFile) {
return NextResponse.json(
{ error: '请选择LOGO文件' },
{ status: 400 }
)
}
if (!logoType || !['header', 'login'].includes(logoType)) {
return NextResponse.json(
{ error: '请指定LOGO类型(header或login)' },
{ status: 400 }
)
}
const allowedImageTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/webp']
if (!allowedImageTypes.includes(logoFile.type)) {
return NextResponse.json(
{ error: '不支持的图片格式,请使用 JPG、PNG 或 WebP 格式' },
{ status: 400 }
)
}
const maxSize = 5 * 1024 * 1024 // 5MB
if (logoFile.size > maxSize) {
return NextResponse.json(
{ error: `LOGO 过大,请使用小于5MB的图片(当前:${(logoFile.size / 1024 / 1024).toFixed(2)}MB)` },
{ status: 400 }
)
}
const originalBuffer = Buffer.from(await logoFile.arrayBuffer())
const processedBuffer = await processImage(originalBuffer, {
maxSizeKB: 300,
maxWidth: 1200,
maxHeight: 400,
format: 'webp',
})
// 生成文件名
const timestamp = Date.now()
const filename = `${logoType}-logo-${timestamp}.webp`
// 上传到S3
const s3Url = await uploadToS3(processedBuffer, filename, 'image/webp')
// 更新系统设置
let settings = await prisma.systemSettings.findFirst()
const fieldName = logoType === 'header' ? 'headerLogoUrl' : 'loginLogoUrl'
if (!settings) {
settings = await prisma.systemSettings.create({
data: {
[fieldName]: s3Url
}
})
} else {
settings = await prisma.systemSettings.update({
where: { id: settings.id },
data: {
[fieldName]: s3Url
}
})
}
return NextResponse.json({
success: true,
logoUrl: s3Url,
type: logoType
})
} catch (error) {
console.error('Upload logo error:', error)
return NextResponse.json(
{ error: '上传LOGO失败' },
{ status: 500 }
)
}
}