File size: 1,426 Bytes
c58940d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
from fastapi import APIRouter, Depends, HTTPException, UploadFile, File
from app.db.supabase import supabase
from app.dependencies.admin_auth import admin_auth
import uuid

router = APIRouter()

ALLOWED_TYPES = ["image/jpeg", "image/png", "image/gif", "image/webp"]
MAX_SIZE = 5 * 1024 * 1024  # 5MB


@router.post("/image", dependencies=[Depends(admin_auth)])
async def upload_image(file: UploadFile = File(...)):
    # Validate file type
    if file.content_type not in ALLOWED_TYPES:
        raise HTTPException(
            status_code=400,
            detail="Invalid file type. Allowed: jpeg, png, gif, webp"
        )

    # Read file content
    content = await file.read()

    # Validate file size
    if len(content) > MAX_SIZE:
        raise HTTPException(status_code=400, detail="File too large. Max size: 5MB")

    # Generate unique filename
    ext = file.filename.split(".")[-1] if file.filename and "." in file.filename else "jpg"
    filename = f"projects/{uuid.uuid4()}.{ext}"

    # Upload to Supabase Storage
    try:
        supabase.storage.from_("images").upload(
            filename,
            content,
            {"content-type": file.content_type}
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Upload failed: {str(e)}")

    # Get public URL
    public_url = supabase.storage.from_("images").get_public_url(filename)

    return {"url": public_url}