hibatorrahmen commited on
Commit
29ce62f
·
1 Parent(s): deb30f5

added auth

Browse files
behavior_backend/main.py CHANGED
@@ -9,6 +9,8 @@ import logging
9
  import time
10
  import os
11
  from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
 
 
12
 
13
  from app.core.config import settings
14
  from app.api.routes.videos import router as videos_router
@@ -26,19 +28,37 @@ logging.basicConfig(level=logging.INFO)
26
  logger = logging.getLogger(__name__)
27
 
28
  # Add security scheme
29
- security = HTTPBearer()
30
 
31
  # Add authentication dependency
32
- async def verify_token(credentials: HTTPAuthorizationCredentials = Depends(security)):
33
- token = credentials.credentials
34
- # You can add more token verification logic here if needed
35
- if not token:
36
- raise HTTPException(
37
- status_code=401,
38
- detail="Invalid authentication credentials",
39
- headers={"WWW-Authenticate": "Bearer"},
40
- )
41
- return token
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
  # Create FastAPI app
44
  app = FastAPI(
@@ -49,10 +69,10 @@ app = FastAPI(
49
  redoc_url="/redoc" # ReDoc UI
50
  )
51
 
52
- # Configure CORS with more specific settings for private Space
53
  app.add_middleware(
54
  CORSMiddleware,
55
- allow_origins=["https://huggingface.co", "https://*.hf.space"],
56
  allow_credentials=True,
57
  allow_methods=["*"],
58
  allow_headers=["*"],
@@ -83,8 +103,8 @@ async def log_requests(request: Request, call_next):
83
  logger.info(f"Path: {request.url.path} Method: {request.method} Time: {process_time:.2f}s Status: {response.status_code}")
84
  return response
85
 
86
- @app.get("/", dependencies=[Depends(verify_token)])
87
- async def root():
88
  """Root endpoint that returns API status"""
89
  return {
90
  "status": "ok",
 
9
  import time
10
  import os
11
  from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
12
+ import jwt
13
+ from typing import Optional
14
 
15
  from app.core.config import settings
16
  from app.api.routes.videos import router as videos_router
 
28
  logger = logging.getLogger(__name__)
29
 
30
  # Add security scheme
31
+ security = HTTPBearer(auto_error=False)
32
 
33
  # Add authentication dependency
34
+ async def verify_token(request: Request, credentials: Optional[HTTPAuthorizationCredentials] = Depends(security)):
35
+ # First check for HF Space JWT token in query params
36
+ hf_token = request.query_params.get("__sign")
37
+ if hf_token:
38
+ try:
39
+ # Verify the JWT token (you may want to add more verification)
40
+ jwt.decode(hf_token, options={"verify_signature": False})
41
+ return hf_token
42
+ except jwt.InvalidTokenError:
43
+ raise HTTPException(status_code=403, detail="Invalid HF Space token")
44
+
45
+ # Then check for Bearer token
46
+ if credentials:
47
+ token = credentials.credentials
48
+ if not token:
49
+ raise HTTPException(
50
+ status_code=401,
51
+ detail="Invalid authentication credentials",
52
+ headers={"WWW-Authenticate": "Bearer"},
53
+ )
54
+ return token
55
+
56
+ # If no token found at all
57
+ raise HTTPException(
58
+ status_code=401,
59
+ detail="Authentication required",
60
+ headers={"WWW-Authenticate": "Bearer"},
61
+ )
62
 
63
  # Create FastAPI app
64
  app = FastAPI(
 
69
  redoc_url="/redoc" # ReDoc UI
70
  )
71
 
72
+ # Configure CORS
73
  app.add_middleware(
74
  CORSMiddleware,
75
+ allow_origins=["*"], # Allow all origins for testing
76
  allow_credentials=True,
77
  allow_methods=["*"],
78
  allow_headers=["*"],
 
103
  logger.info(f"Path: {request.url.path} Method: {request.method} Time: {process_time:.2f}s Status: {response.status_code}")
104
  return response
105
 
106
+ @app.get("/")
107
+ async def root(token: str = Depends(verify_token)):
108
  """Root endpoint that returns API status"""
109
  return {
110
  "status": "ok",
behavior_backend/requirements.txt CHANGED
@@ -19,6 +19,7 @@ python-dotenv==1.0.1
19
  cryptography==44.0.2
20
  bcrypt==4.0.1
21
  email_validator==2.2.0
 
22
 
23
  # File Handling
24
  aiofiles==23.2.1
 
19
  cryptography==44.0.2
20
  bcrypt==4.0.1
21
  email_validator==2.2.0
22
+ PyJWT==2.8.0
23
 
24
  # File Handling
25
  aiofiles==23.2.1