summaryrefslogtreecommitdiff
path: root/app/api/revision-upload/route.ts
diff options
context:
space:
mode:
Diffstat (limited to 'app/api/revision-upload/route.ts')
-rw-r--r--app/api/revision-upload/route.ts175
1 files changed, 125 insertions, 50 deletions
diff --git a/app/api/revision-upload/route.ts b/app/api/revision-upload/route.ts
index 1a9666a7..b171b89a 100644
--- a/app/api/revision-upload/route.ts
+++ b/app/api/revision-upload/route.ts
@@ -1,9 +1,5 @@
import { NextRequest, NextResponse } from "next/server"
-import { writeFile } from "fs/promises"
-import { join } from "path"
-import { v4 as uuidv4 } from "uuid"
-import path from "path"
-import { revalidateTag } from "next/cache" // ✅ 추가
+import { revalidateTag } from "next/cache"
import db from "@/db/db"
import {
@@ -14,7 +10,10 @@ import {
} from "@/db/schema/vendorDocu"
import { and, eq } from "drizzle-orm"
-/* ① change log 유틸 */
+/* 보안 강화된 파일 저장 유틸리티 */
+import { saveFile, SaveFileResult } from "@/lib/file-stroage"
+
+/* change log 유틸 */
import {
logRevisionChange,
logAttachmentChange,
@@ -29,8 +28,8 @@ export async function POST(request: NextRequest) {
const revision = formData.get("revision") as string | null
const docId = Number(formData.get("documentId"))
const uploaderName = formData.get("uploaderName") as string | null
- const usage = formData.get("usage") as string | null
- const usageType = formData.get("usageType") as string | null
+ const usage = formData.get("usage") as string | null
+ const usageType = formData.get("usageType") as string | null
const comment = formData.get("comment") as string | null
const mode = (formData.get("mode") || "new") as string // 'new'|'append'
const targetSystem = (formData.get("targetSystem") as string | null) ?? "DOLCE"
@@ -44,24 +43,31 @@ export async function POST(request: NextRequest) {
if (!attachmentFiles.length)
return NextResponse.json({ error: "No files provided" }, { status: 400 })
+ // 기본 파일 크기 검증 (보안 함수에서도 검증하지만 조기 체크)
const MAX = 3 * 1024 * 1024 * 1024 // 3 GB
- for (const f of attachmentFiles)
- if (f.size > MAX)
+ for (const f of attachmentFiles) {
+ if (f.size > MAX) {
return NextResponse.json(
{ error: `${f.name} > 3 GB` },
{ status: 400 }
)
+ }
+ }
/* ------- 계약 ID 확보 ------- */
- const [{ contractId }] = await db
+ const [docInfo] = await db
.select({ contractId: documents.contractId })
.from(documents)
.where(eq(documents.id, docId))
.limit(1)
+ if (!docInfo) {
+ return NextResponse.json({ error: "Document not found" }, { status: 404 })
+ }
+
/* ------- 트랜잭션 ------- */
const result = await db.transaction(async (tx) => {
- /* 1) Stage */
+ /* 1) Stage 생성/조회 */
let issueStageId: number
const [stageRow] = await tx
.select({ id: issueStages.id })
@@ -77,9 +83,11 @@ export async function POST(request: NextRequest) {
.values({ documentId: docId, stageName: stage, updatedAt: new Date() })
.returning({ id: issueStages.id })
issueStageId = s.id
- } else issueStageId = stageRow.id
+ } else {
+ issueStageId = stageRow.id
+ }
- /* 2) Revision */
+ /* 2) Revision 생성/업데이트 */
const today = new Date().toISOString().slice(0, 10)
let revisionId: number
const [revRow] = await tx
@@ -93,23 +101,30 @@ export async function POST(request: NextRequest) {
if (!revRow || mode === "new") {
/* --- CREATE --- */
+ const revisionData: any = {
+ issueStageId,
+ revision,
+ uploaderType: "vendor",
+ uploaderName: uploaderName ?? undefined,
+ revisionStatus: "UPLOADED",
+ uploadedAt: today,
+ comment: comment ?? undefined,
+ updatedAt: new Date(),
+ }
+
+ // usage와 usageType이 있으면 추가
+ if (usage) revisionData.usage = usage
+ if (usageType) revisionData.usageType = usageType
+
const [newRev] = await tx.insert(revisions)
- .values({
- issueStageId,
- revision,
- uploaderType: "vendor",
- uploaderName: uploaderName ?? undefined,
- revisionStatus: "UPLOADED",
- uploadedAt: today,
- comment: comment ?? undefined,
- updatedAt: new Date(),
- })
+ .values(revisionData)
.returning()
+
revisionId = newRev.id
// change_logs: CREATE
await logRevisionChange(
- contractId,
+ docInfo.contractId,
revisionId,
"CREATE",
newRev,
@@ -120,12 +135,18 @@ export async function POST(request: NextRequest) {
)
} else {
/* --- UPDATE --- */
+ const updateData: any = {
+ uploaderName: uploaderName ?? revRow.uploaderName,
+ comment: comment ?? revRow.comment,
+ updatedAt: new Date(),
+ }
+
+ // usage와 usageType이 있으면 업데이트
+ if (usage) updateData.usage = usage
+ if (usageType) updateData.usageType = usageType
+
await tx.update(revisions)
- .set({
- uploaderName: uploaderName ?? revRow.uploaderName,
- comment: comment ?? revRow.comment,
- updatedAt: new Date(),
- })
+ .set(updateData)
.where(eq(revisions.id, revRow.id))
const [updated] = await tx
@@ -136,7 +157,7 @@ export async function POST(request: NextRequest) {
revisionId = revRow.id
await logRevisionChange(
- contractId,
+ docInfo.contractId,
revisionId,
"UPDATE",
updated,
@@ -147,38 +168,54 @@ export async function POST(request: NextRequest) {
)
}
- /* 3) Attachments */
+ /* ------- 보안 강화된 첨부파일 처리 ------- */
const uploadedFiles: any[] = []
- const baseDir = join(process.cwd(), "public", "documents")
+ const securityFailures: string[] = []
for (const file of attachmentFiles) {
- const ext = path.extname(file.name)
- const fname = uuidv4() + ext
- const dest = join(baseDir, fname)
+ console.log(`🔐 보안 검증 시작: ${file.name}`)
+
+ // 보안 강화된 파일 저장
+ const saveResult: SaveFileResult = await saveFile({
+ file,
+ directory: "documents", // 문서 전용 디렉토리
+ originalName: file.name,
+ userId: uploaderName || "anonymous", // 업로더 정보 로깅용
+ })
+
+ if (!saveResult.success) {
+ console.error(`❌ 파일 보안 검증 실패: ${file.name} - ${saveResult.error}`)
+ securityFailures.push(`${file.name}: ${saveResult.error}`)
+ continue // 실패한 파일은 건너뛰고 계속 진행
+ }
- await writeFile(dest, Buffer.from(await file.arrayBuffer()))
+ console.log(`✅ 파일 보안 검증 통과: ${file.name}`)
+ console.log(`📁 저장된 경로: ${saveResult.publicPath}`)
+ // DB에 첨부파일 정보 저장
const [att] = await tx.insert(documentAttachments)
.values({
revisionId,
- fileName: file.name,
- filePath: "/documents/" + fname,
- fileSize: file.size,
- fileType: ext.slice(1).toLowerCase() || undefined,
+ fileName: saveResult.originalName!, // 원본 파일명
+ filePath: saveResult.publicPath!, // 웹 접근 경로
+ fileSize: saveResult.fileSize!,
+ fileType: saveResult.fileName!.split('.').pop()?.toLowerCase() || undefined,
updatedAt: new Date(),
})
.returning()
uploadedFiles.push({
id: att.id,
- fileName: file.name,
- fileSize: file.size,
- filePath: att.filePath,
+ fileName: saveResult.originalName,
+ fileSize: saveResult.fileSize,
+ filePath: saveResult.publicPath,
+ fileType: saveResult.fileName!.split('.').pop()?.toLowerCase() || null,
+ securityChecks: saveResult.securityChecks, // 보안 검증 결과
})
// change_logs: attachment CREATE
await logAttachmentChange(
- contractId,
+ docInfo.contractId,
att.id,
"CREATE",
att,
@@ -189,15 +226,35 @@ export async function POST(request: NextRequest) {
)
}
- /* 4) documents.updatedAt */
+ // 보안 검증 실패한 파일이 있으면 경고 반환
+ if (securityFailures.length > 0) {
+ console.warn(`⚠️ 일부 파일의 보안 검증 실패:`, securityFailures)
+
+ // 모든 파일이 실패한 경우 에러 반환
+ if (uploadedFiles.length === 0) {
+ throw new Error(`모든 파일의 보안 검증이 실패했습니다: ${securityFailures.join(', ')}`)
+ }
+ }
+
+ /* 4) documents.updatedAt 업데이트 */
await tx.update(documents)
.set({ updatedAt: new Date() })
.where(eq(documents.id, docId))
- return { revisionId, stage, revision, uploadedFiles, mode, contractId }
+ return {
+ revisionId,
+ stage,
+ revision,
+ uploadedFiles,
+ mode,
+ contractId: docInfo.contractId,
+ usage,
+ usageType,
+ securityFailures // 보안 실패 정보 포함
+ }
})
- // ✅ 캐시 무효화 - 트랜잭션 완료 후에 실행
+ // 캐시 무효화 - 트랜잭션 완료 후에 실행
try {
// enhanced documents 캐시 무효화
revalidateTag(`enhanced-documents-${result.contractId}`)
@@ -211,10 +268,28 @@ export async function POST(request: NextRequest) {
// 캐시 무효화 실패해도 업로드는 성공으로 처리
}
+ // 응답 메시지 구성
+ let message = `${result.uploadedFiles.length}개 파일 업로드 완료`
+ if (result.securityFailures.length > 0) {
+ message += ` (일부 파일 보안 검증 실패: ${result.securityFailures.length}개)`
+ }
+
return NextResponse.json({
success: true,
- message: `${result.uploadedFiles.length}개 파일 업로드 완료`,
- data: result,
+ message,
+ data: {
+ revisionId: result.revisionId,
+ stage: result.stage,
+ revision: result.revision,
+ mode: result.mode,
+ usage: result.usage,
+ usageType: result.usageType,
+ uploaderName: uploaderName,
+ uploadedFiles: result.uploadedFiles,
+ filesCount: result.uploadedFiles.length,
+ securityFailures: result.securityFailures, // 클라이언트에 보안 실패 정보 전달
+ contractId: result.contractId,
+ },
})
} catch (e) {
console.error("revision-upload error:", e)