|
1 | 1 | import { eq, sql } from 'drizzle-orm' |
2 | 2 | import { type NextRequest, NextResponse } from 'next/server' |
| 3 | +import { z } from 'zod' |
3 | 4 | import { getSession } from '@/lib/auth' |
4 | 5 | import { createLogger } from '@/lib/logs/console/logger' |
| 6 | +import { hasAdminPermission } from '@/lib/permissions/utils' |
5 | 7 | import { db } from '@/db' |
6 | | -import { templates } from '@/db/schema' |
| 8 | +import { templates, workflow } from '@/db/schema' |
7 | 9 |
|
8 | 10 | const logger = createLogger('TemplateByIdAPI') |
9 | 11 |
|
@@ -62,3 +64,153 @@ export async function GET(request: NextRequest, { params }: { params: Promise<{ |
62 | 64 | return NextResponse.json({ error: 'Internal server error' }, { status: 500 }) |
63 | 65 | } |
64 | 66 | } |
| 67 | + |
| 68 | +const updateTemplateSchema = z.object({ |
| 69 | + name: z.string().min(1).max(100), |
| 70 | + description: z.string().min(1).max(500), |
| 71 | + author: z.string().min(1).max(100), |
| 72 | + category: z.string().min(1), |
| 73 | + icon: z.string().min(1), |
| 74 | + color: z.string().regex(/^#[0-9A-F]{6}$/i), |
| 75 | + state: z.any().optional(), // Workflow state |
| 76 | +}) |
| 77 | + |
| 78 | +// PUT /api/templates/[id] - Update a template |
| 79 | +export async function PUT(request: NextRequest, { params }: { params: Promise<{ id: string }> }) { |
| 80 | + const requestId = crypto.randomUUID().slice(0, 8) |
| 81 | + const { id } = await params |
| 82 | + |
| 83 | + try { |
| 84 | + const session = await getSession() |
| 85 | + if (!session?.user?.id) { |
| 86 | + logger.warn(`[${requestId}] Unauthorized template update attempt for ID: ${id}`) |
| 87 | + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) |
| 88 | + } |
| 89 | + |
| 90 | + const body = await request.json() |
| 91 | + const validationResult = updateTemplateSchema.safeParse(body) |
| 92 | + |
| 93 | + if (!validationResult.success) { |
| 94 | + logger.warn(`[${requestId}] Invalid template data for update: ${id}`, validationResult.error) |
| 95 | + return NextResponse.json( |
| 96 | + { error: 'Invalid template data', details: validationResult.error.errors }, |
| 97 | + { status: 400 } |
| 98 | + ) |
| 99 | + } |
| 100 | + |
| 101 | + const { name, description, author, category, icon, color, state } = validationResult.data |
| 102 | + |
| 103 | + // Check if template exists |
| 104 | + const existingTemplate = await db.select().from(templates).where(eq(templates.id, id)).limit(1) |
| 105 | + |
| 106 | + if (existingTemplate.length === 0) { |
| 107 | + logger.warn(`[${requestId}] Template not found for update: ${id}`) |
| 108 | + return NextResponse.json({ error: 'Template not found' }, { status: 404 }) |
| 109 | + } |
| 110 | + |
| 111 | + // Permission: template owner OR admin of the workflow's workspace (if any) |
| 112 | + let canUpdate = existingTemplate[0].userId === session.user.id |
| 113 | + |
| 114 | + if (!canUpdate && existingTemplate[0].workflowId) { |
| 115 | + const wfRows = await db |
| 116 | + .select({ workspaceId: workflow.workspaceId }) |
| 117 | + .from(workflow) |
| 118 | + .where(eq(workflow.id, existingTemplate[0].workflowId)) |
| 119 | + .limit(1) |
| 120 | + |
| 121 | + const workspaceId = wfRows[0]?.workspaceId as string | null | undefined |
| 122 | + if (workspaceId) { |
| 123 | + const hasAdmin = await hasAdminPermission(session.user.id, workspaceId) |
| 124 | + if (hasAdmin) canUpdate = true |
| 125 | + } |
| 126 | + } |
| 127 | + |
| 128 | + if (!canUpdate) { |
| 129 | + logger.warn(`[${requestId}] User denied permission to update template ${id}`) |
| 130 | + return NextResponse.json({ error: 'Access denied' }, { status: 403 }) |
| 131 | + } |
| 132 | + |
| 133 | + // Update the template |
| 134 | + const updatedTemplate = await db |
| 135 | + .update(templates) |
| 136 | + .set({ |
| 137 | + name, |
| 138 | + description, |
| 139 | + author, |
| 140 | + category, |
| 141 | + icon, |
| 142 | + color, |
| 143 | + ...(state && { state }), |
| 144 | + updatedAt: new Date(), |
| 145 | + }) |
| 146 | + .where(eq(templates.id, id)) |
| 147 | + .returning() |
| 148 | + |
| 149 | + logger.info(`[${requestId}] Successfully updated template: ${id}`) |
| 150 | + |
| 151 | + return NextResponse.json({ |
| 152 | + data: updatedTemplate[0], |
| 153 | + message: 'Template updated successfully', |
| 154 | + }) |
| 155 | + } catch (error: any) { |
| 156 | + logger.error(`[${requestId}] Error updating template: ${id}`, error) |
| 157 | + return NextResponse.json({ error: 'Internal server error' }, { status: 500 }) |
| 158 | + } |
| 159 | +} |
| 160 | + |
| 161 | +// DELETE /api/templates/[id] - Delete a template |
| 162 | +export async function DELETE( |
| 163 | + request: NextRequest, |
| 164 | + { params }: { params: Promise<{ id: string }> } |
| 165 | +) { |
| 166 | + const requestId = crypto.randomUUID().slice(0, 8) |
| 167 | + const { id } = await params |
| 168 | + |
| 169 | + try { |
| 170 | + const session = await getSession() |
| 171 | + if (!session?.user?.id) { |
| 172 | + logger.warn(`[${requestId}] Unauthorized template delete attempt for ID: ${id}`) |
| 173 | + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) |
| 174 | + } |
| 175 | + |
| 176 | + // Fetch template |
| 177 | + const existing = await db.select().from(templates).where(eq(templates.id, id)).limit(1) |
| 178 | + if (existing.length === 0) { |
| 179 | + logger.warn(`[${requestId}] Template not found for delete: ${id}`) |
| 180 | + return NextResponse.json({ error: 'Template not found' }, { status: 404 }) |
| 181 | + } |
| 182 | + |
| 183 | + const template = existing[0] |
| 184 | + |
| 185 | + // Permission: owner or admin of the workflow's workspace (if any) |
| 186 | + let canDelete = template.userId === session.user.id |
| 187 | + |
| 188 | + if (!canDelete && template.workflowId) { |
| 189 | + // Look up workflow to get workspaceId |
| 190 | + const wfRows = await db |
| 191 | + .select({ workspaceId: workflow.workspaceId }) |
| 192 | + .from(workflow) |
| 193 | + .where(eq(workflow.id, template.workflowId)) |
| 194 | + .limit(1) |
| 195 | + |
| 196 | + const workspaceId = wfRows[0]?.workspaceId as string | null | undefined |
| 197 | + if (workspaceId) { |
| 198 | + const hasAdmin = await hasAdminPermission(session.user.id, workspaceId) |
| 199 | + if (hasAdmin) canDelete = true |
| 200 | + } |
| 201 | + } |
| 202 | + |
| 203 | + if (!canDelete) { |
| 204 | + logger.warn(`[${requestId}] User denied permission to delete template ${id}`) |
| 205 | + return NextResponse.json({ error: 'Access denied' }, { status: 403 }) |
| 206 | + } |
| 207 | + |
| 208 | + await db.delete(templates).where(eq(templates.id, id)) |
| 209 | + |
| 210 | + logger.info(`[${requestId}] Deleted template: ${id}`) |
| 211 | + return NextResponse.json({ success: true }) |
| 212 | + } catch (error: any) { |
| 213 | + logger.error(`[${requestId}] Error deleting template: ${id}`, error) |
| 214 | + return NextResponse.json({ error: 'Internal server error' }, { status: 500 }) |
| 215 | + } |
| 216 | +} |
0 commit comments