|
| 1 | +import { db } from '@sim/db' |
| 2 | +import { knowledgeBase } from '@sim/db/schema' |
| 3 | +import { createLogger } from '@sim/logger' |
| 4 | +import { eq } from 'drizzle-orm' |
| 5 | +import { type NextRequest, NextResponse } from 'next/server' |
| 6 | +import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid' |
| 7 | +import { generateRequestId } from '@/lib/core/utils/request' |
| 8 | +import { restoreKnowledgeBase } from '@/lib/knowledge/service' |
| 9 | +import { getUserEntityPermissions } from '@/lib/workspaces/permissions/utils' |
| 10 | + |
| 11 | +const logger = createLogger('RestoreKnowledgeBaseAPI') |
| 12 | + |
| 13 | +export async function POST( |
| 14 | + request: NextRequest, |
| 15 | + { params }: { params: Promise<{ id: string }> } |
| 16 | +) { |
| 17 | + const requestId = generateRequestId() |
| 18 | + const { id } = await params |
| 19 | + |
| 20 | + try { |
| 21 | + const auth = await checkSessionOrInternalAuth(request, { requireWorkflowId: false }) |
| 22 | + if (!auth.success || !auth.userId) { |
| 23 | + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) |
| 24 | + } |
| 25 | + |
| 26 | + const [kb] = await db |
| 27 | + .select({ |
| 28 | + id: knowledgeBase.id, |
| 29 | + workspaceId: knowledgeBase.workspaceId, |
| 30 | + userId: knowledgeBase.userId, |
| 31 | + }) |
| 32 | + .from(knowledgeBase) |
| 33 | + .where(eq(knowledgeBase.id, id)) |
| 34 | + .limit(1) |
| 35 | + |
| 36 | + if (!kb) { |
| 37 | + return NextResponse.json({ error: 'Knowledge base not found' }, { status: 404 }) |
| 38 | + } |
| 39 | + |
| 40 | + if (kb.workspaceId) { |
| 41 | + const permission = await getUserEntityPermissions(auth.userId, 'workspace', kb.workspaceId) |
| 42 | + if (permission !== 'admin' && permission !== 'write') { |
| 43 | + return NextResponse.json({ error: 'Insufficient permissions' }, { status: 403 }) |
| 44 | + } |
| 45 | + } else if (kb.userId !== auth.userId) { |
| 46 | + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) |
| 47 | + } |
| 48 | + |
| 49 | + await restoreKnowledgeBase(id, requestId) |
| 50 | + |
| 51 | + logger.info(`[${requestId}] Restored knowledge base ${id}`) |
| 52 | + |
| 53 | + return NextResponse.json({ success: true }) |
| 54 | + } catch (error) { |
| 55 | + logger.error(`[${requestId}] Error restoring knowledge base ${id}`, error) |
| 56 | + return NextResponse.json( |
| 57 | + { error: error instanceof Error ? error.message : 'Internal server error' }, |
| 58 | + { status: 500 } |
| 59 | + ) |
| 60 | + } |
| 61 | +} |
0 commit comments