Spaces:
Sleeping

axeronis commited on
Commit
72d27f1
·
1 Parent(s): 0f84c85

fix(products): finalize supabase storage implementation

Browse files
Files changed (1) hide show
  1. backend/app/api/products.py +44 -17
backend/app/api/products.py CHANGED
@@ -218,23 +218,50 @@ async def upload_product_image(
218
  - Cloudinary
219
  - Supabase Storage
220
  """
221
- # TODO: Implement actual file upload to cloud storage
222
- # For now, return a placeholder response
223
-
224
- if not file.content_type or not file.content_type.startswith("image/"):
225
  raise HTTPException(
226
- status_code=status.HTTP_400_BAD_REQUEST,
227
- detail="File must be an image"
228
  )
229
 
230
- # Placeholder: In production, upload to S3/Cloudinary/Supabase Storage
231
- # Example with Supabase:
232
- # from app.core.config import settings
233
- # supabase_client.storage.from_('products').upload(f"{current_user.tenant_id}/{file.filename}", file.file)
234
- # url = supabase_client.storage.from_('products').get_public_url(f"{current_user.tenant_id}/{file.filename}")
235
-
236
- return {
237
- "url": f"https://placeholder.com/products/{file.filename}",
238
- "filename": file.filename,
239
- "content_type": file.content_type
240
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
218
  - Cloudinary
219
  - Supabase Storage
220
  """
221
+ # 1. Initialize Supabase
222
+ from app.core.supabase import supabase_client
223
+ if not supabase_client:
 
224
  raise HTTPException(
225
+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
226
+ detail="Supabase Storage not configured"
227
  )
228
 
229
+ # 2. Sanitize filename & Rename to avoid collisions
230
+ # Format: {tenant_id}/{timestamp}_{safe_filename}
231
+ import re
232
+ import time
233
+
234
+ timestamp = int(time.time())
235
+ safe_filename = re.sub(r'[^a-zA-Z0-9_\-\.]', '_', file.filename)
236
+ if len(safe_filename) > 50:
237
+ safe_filename = safe_filename[-50:]
238
+
239
+ # Tenant isolation folder
240
+ storage_path = f"{current_user.tenant_id}/{timestamp}_{safe_filename}"
241
+
242
+ # 3. Read file content
243
+ file_content = await file.read()
244
+
245
+ try:
246
+ # 4. Upload to Supabase 'products' bucket
247
+ res = supabase_client.storage.from_("products").upload(
248
+ path=storage_path,
249
+ file=file_content,
250
+ file_options={"content-type": file.content_type}
251
+ )
252
+
253
+ # 5. Get Public URL
254
+ public_url = supabase_client.storage.from_("products").get_public_url(storage_path)
255
+
256
+ return {
257
+ "url": public_url,
258
+ "filename": safe_filename,
259
+ "content_type": file.content_type
260
+ }
261
+
262
+ except Exception as e:
263
+ print(f"❌ Storage Upload Error: {e}")
264
+ raise HTTPException(
265
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
266
+ detail=f"Upload failed: {str(e)}"
267
+ )