Spaces:
Sleeping
Sleeping
Create main.py
Browse files
main.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from fastapi import FastAPI, Header, HTTPException
|
| 3 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 4 |
+
from supabase import create_client, Client
|
| 5 |
+
from jose import jwt, JWTError
|
| 6 |
+
from dotenv import load_dotenv
|
| 7 |
+
|
| 8 |
+
# Load environment variables from .env file for local development
|
| 9 |
+
load_dotenv()
|
| 10 |
+
|
| 11 |
+
# --- Configuration ---
|
| 12 |
+
# These will be set as "Secrets" in your Hugging Face Space settings
|
| 13 |
+
SUPABASE_URL = os.getenv("SUPABASE_URL")
|
| 14 |
+
SUPABASE_SERVICE_KEY = os.getenv("SUPABASE_SERVICE_ROLE_KEY")
|
| 15 |
+
JWT_SECRET_KEY = os.getenv("JWT_SECRET_KEY")
|
| 16 |
+
ALGORITHM = "HS256"
|
| 17 |
+
# This should be the URL of your deployed frontend app (e.g., Vercel)
|
| 18 |
+
FRONTEND_URL = os.getenv("FRONTEND_URL", "http://localhost:3000")
|
| 19 |
+
|
| 20 |
+
# --- Initialization ---
|
| 21 |
+
app = FastAPI()
|
| 22 |
+
|
| 23 |
+
# Initialize Supabase client with the service role key for admin access
|
| 24 |
+
try:
|
| 25 |
+
supabase: Client = create_client(SUPABASE_URL, SUPABASE_SERVICE_KEY)
|
| 26 |
+
except Exception as e:
|
| 27 |
+
print(f"Error initializing Supabase client: {e}")
|
| 28 |
+
supabase = None
|
| 29 |
+
|
| 30 |
+
# Configure CORS (Cross-Origin Resource Sharing)
|
| 31 |
+
# This allows your frontend to make requests to this backend
|
| 32 |
+
app.add_middleware(
|
| 33 |
+
CORSMiddleware,
|
| 34 |
+
allow_origins=[FRONTEND_URL], # The origin of your frontend app
|
| 35 |
+
allow_credentials=True,
|
| 36 |
+
allow_methods=["*"],
|
| 37 |
+
allow_headers=["*"],
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
# --- API Endpoint ---
|
| 41 |
+
@app.get("/get-itinerary")
|
| 42 |
+
async def get_itinerary_data(authorization: str = Header(...)):
|
| 43 |
+
"""
|
| 44 |
+
Verifies the user's custom JWT and fetches their itinerary from Supabase.
|
| 45 |
+
"""
|
| 46 |
+
if not supabase:
|
| 47 |
+
raise HTTPException(status_code=500, detail="Database connection not configured.")
|
| 48 |
+
|
| 49 |
+
try:
|
| 50 |
+
# 1. Extract token from "Bearer <token>" header
|
| 51 |
+
token_type, token = authorization.split()
|
| 52 |
+
if token_type.lower() != "bearer":
|
| 53 |
+
raise HTTPException(status_code=401, detail="Invalid token type")
|
| 54 |
+
|
| 55 |
+
# 2. Verify and decode the JWT
|
| 56 |
+
payload = jwt.decode(token, JWT_SECRET_KEY, algorithms=[ALGORITHM])
|
| 57 |
+
|
| 58 |
+
# 3. Extract user ID (adjust 'id' to match the key in your JWT payload)
|
| 59 |
+
user_id = payload.get("id")
|
| 60 |
+
if user_id is None:
|
| 61 |
+
raise HTTPException(status_code=401, detail="User ID not found in token payload")
|
| 62 |
+
|
| 63 |
+
# 4. Query Supabase for the itinerary data
|
| 64 |
+
# Using the admin client bypasses RLS, which is what we want here
|
| 65 |
+
response = supabase.table("itineraries").select("itinerary_data").eq("user_id", user_id).single().execute()
|
| 66 |
+
|
| 67 |
+
# Check for errors from Supabase (e.g., no rows found)
|
| 68 |
+
if not response.data:
|
| 69 |
+
raise HTTPException(status_code=404, detail="Itinerary not found for this user")
|
| 70 |
+
|
| 71 |
+
# 5. Return the data
|
| 72 |
+
return response.data
|
| 73 |
+
|
| 74 |
+
except JWTError:
|
| 75 |
+
raise HTTPException(status_code=401, detail="Could not validate credentials")
|
| 76 |
+
except HTTPException as e:
|
| 77 |
+
# Re-raise HTTPExceptions to preserve status code and detail
|
| 78 |
+
raise e
|
| 79 |
+
except Exception as e:
|
| 80 |
+
# Catch any other unexpected errors
|
| 81 |
+
print(f"An unexpected error occurred: {e}")
|
| 82 |
+
raise HTTPException(status_code=500, detail="Internal server error")
|