| 1 | import { and, eq } from 'drizzle-orm' |
| 2 | import { NextResponse } |
| 3 | import { getSession } |
| 4 | import { db } |
| 5 | import { media, members |
| 6 | import { s3Service } |
| 7 | |
| 8 | const MAX_SIZE = 10 |
| 9 | const ALLOWED_TYPES = [ |
| 10 | 'image/jpeg', |
| 11 | 'image/png', |
| 12 | 'image/gif', |
| 13 | 'image/webp', |
| 14 | 'image/svg+xml', |
| 15 | ] |
| 16 | |
| 17 | export async function POST |
| 18 | const session = |
| 19 | if (!session) |
| 20 | return NextResponse.json |
| 21 | } |
| 22 | |
| 23 | const formData = |
| 24 | const file = |
| 25 | const projectId = |
| 26 | |
| 27 | if (!file) |
| 28 | return NextResponse.json |
| 29 | } |
| 30 | |
| 31 | if (!projectId) |
| 32 | return NextResponse.json |
| 33 | { error: 'projectId is required' |
| 34 | { status: 400 } |
| 35 | ) |
| 36 | } |
| 37 | |
| 38 | if (!ALLOWED_TYPES.includes |
| 39 | return NextResponse.json |
| 40 | { error: 'File type not allowed. Use JPEG, PNG, GIF, WebP, or SVG.' |
| 41 | { status: 400 } |
| 42 | ) |
| 43 | } |
| 44 | |
| 45 | if (file.size |
| 46 | return NextResponse.json |
| 47 | { error: 'File too large. Maximum size is 5MB.' |
| 48 | { status: 400 } |
| 49 | ) |
| 50 | } |
| 51 | |
| 52 | // Verify the project exists and user is a member of its org |
| 53 | const [project] |
| 54 | .select({ id: |
| 55 | .from(projects) |
| 56 | .where(eq(projects |
| 57 | |
| 58 | if (!project) |
| 59 | return NextResponse.json |
| 60 | } |
| 61 | |
| 62 | const [member] |
| 63 | .select({ id: |
| 64 | .from(members) |
| 65 | .where( |
| 66 | and( |
| 67 | eq(members.userId |
| 68 | eq(members.organizationId |
| 69 | ) |
| 70 | ) |
| 71 | |
| 72 | if (!member) |
| 73 | return NextResponse.json |
| 74 | } |
| 75 | |
| 76 | const buffer = |
| 77 | const { key |
| 78 | buffer, |
| 79 | file.type, |
| 80 | `uploads/${projectId}` |
| 81 | ) |
| 82 | |
| 83 | const url = |
| 84 | |
| 85 | // Save to media library for reuse across the organization |
| 86 | const [mediaRecord] |
| 87 | .insert(media) |
| 88 | .values({ |
| 89 | organizationId: project.organizationId |
| 90 | uploadedByMemberId: member.id |
| 91 | name: file.name |
| 92 | key, |
| 93 | url, |
| 94 | contentType: file.type |
| 95 | size: file.size |
| 96 | }) |
| 97 | .returning({ id: |
| 98 | |
| 99 | // Return the internal URL that goes through our auth-gated files route |
| 100 | return NextResponse.json |
| 101 | } |