Spaces:
Sleeping
Sleeping
File size: 2,411 Bytes
91990f9 | 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 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | import random
import string
from fastapi import APIRouter, HTTPException, Request
from config.database import get_supabase_admin
from middleware.auth_guard import get_current_user
router = APIRouter(prefix="/api/share", tags=["share"])
def _generate_code(length=8) -> str:
return ''.join(random.choices(string.ascii_letters + string.digits, k=length))
@router.post("/create")
async def create_share(request: Request):
user = await get_current_user(request)
body = await request.json()
analysis_id = body.get("analysis_id")
if not analysis_id:
raise HTTPException(status_code=400, detail="analysis_id is required")
db = get_supabase_admin()
# Verify the analysis belongs to this user
analysis = db.table("analyses").select("id").eq("id", analysis_id).eq("user_id", str(user.id)).single().execute()
if not analysis.data:
raise HTTPException(status_code=404, detail="Analysis not found")
# Generate unique short code
for _ in range(5):
code = _generate_code()
existing = db.table("shared_analyses").select("id").eq("short_code", code).execute()
if not existing.data:
break
result = db.table("shared_analyses").insert({
"analysis_id": analysis_id,
"short_code": code,
"is_public": True,
}).execute()
return {"short_code": code, "url": f"https://codenexus.qzz.io/share/{code}"}
@router.get("/{code}")
async def get_shared_analysis(code: str):
db = get_supabase_admin()
shared = db.table("shared_analyses").select("*, analyses(*)").eq("short_code", code).eq("is_public", True).single().execute()
if not shared.data:
raise HTTPException(status_code=404, detail="Shared analysis not found or has been removed")
return shared.data
@router.delete("/{code}")
async def delete_share(code: str, request: Request):
user = await get_current_user(request)
db = get_supabase_admin()
shared = db.table("shared_analyses").select("*, analyses(user_id)").eq("short_code", code).single().execute()
if not shared.data:
raise HTTPException(status_code=404, detail="Share not found")
if shared.data["analyses"]["user_id"] != str(user.id):
raise HTTPException(status_code=403, detail="Not your share link")
db.table("shared_analyses").delete().eq("short_code", code).execute()
return {"message": "Share link deleted"}
|