Spaces:
Running
Running
Commit
·
97068b2
1
Parent(s):
1331365
Fix dependencies import conflict
Browse files- Remove backend/dependencies/ directory (conflicted with existing file)
- Add authentication functions to existing backend/dependencies.py
- Update import in app.py to use correct module
- Maintain all existing database dependencies (get_db_session, etc.)
- Should fix import error on startup
- backend/app.py +1 -1
- backend/dependencies.py +94 -3
- backend/dependencies/__init__.py +0 -25
- backend/dependencies/auth.py +0 -128
backend/app.py
CHANGED
|
@@ -15,7 +15,7 @@ from starlette.middleware.sessions import SessionMiddleware
|
|
| 15 |
from fastapi.responses import RedirectResponse, HTMLResponse
|
| 16 |
from backend.middleware.auth import ConditionalAuthMiddleware
|
| 17 |
from backend.middleware.usage_tracker import UsageTrackingMiddleware
|
| 18 |
-
from backend.dependencies
|
| 19 |
from utils.environment import should_enable_auth, debug_environment
|
| 20 |
|
| 21 |
|
|
|
|
| 15 |
from fastapi.responses import RedirectResponse, HTMLResponse
|
| 16 |
from backend.middleware.auth import ConditionalAuthMiddleware
|
| 17 |
from backend.middleware.usage_tracker import UsageTrackingMiddleware
|
| 18 |
+
from backend.dependencies import require_auth_in_hf_spaces
|
| 19 |
from utils.environment import should_enable_auth, debug_environment
|
| 20 |
|
| 21 |
|
backend/dependencies.py
CHANGED
|
@@ -3,8 +3,9 @@ Dependencies for FastAPI routes
|
|
| 3 |
"""
|
| 4 |
|
| 5 |
import logging
|
| 6 |
-
from typing import Generator, Optional, Any
|
| 7 |
-
from fastapi import Depends, HTTPException, status
|
|
|
|
| 8 |
|
| 9 |
# Initialize global testers
|
| 10 |
knowledge_graph_tester = None
|
|
@@ -90,4 +91,94 @@ def get_prompt_reconstructor() -> Any:
|
|
| 90 |
detail=f"Error initializing reconstructor: {str(e)}"
|
| 91 |
)
|
| 92 |
|
| 93 |
-
return prompt_reconstructor
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
"""
|
| 4 |
|
| 5 |
import logging
|
| 6 |
+
from typing import Generator, Optional, Any, Dict
|
| 7 |
+
from fastapi import Depends, HTTPException, status, Request
|
| 8 |
+
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
| 9 |
|
| 10 |
# Initialize global testers
|
| 11 |
knowledge_graph_tester = None
|
|
|
|
| 91 |
detail=f"Error initializing reconstructor: {str(e)}"
|
| 92 |
)
|
| 93 |
|
| 94 |
+
return prompt_reconstructor
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
# ===== AUTHENTICATION DEPENDENCIES =====
|
| 98 |
+
|
| 99 |
+
# Optional security scheme for Bearer tokens
|
| 100 |
+
security = HTTPBearer(auto_error=False)
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def get_current_user_optional(request: Request) -> Optional[Dict[str, Any]]:
|
| 104 |
+
"""
|
| 105 |
+
Get current user from session, but don't raise error if not found.
|
| 106 |
+
Used for endpoints where authentication is optional.
|
| 107 |
+
"""
|
| 108 |
+
from utils.environment import should_enable_auth
|
| 109 |
+
|
| 110 |
+
if not should_enable_auth():
|
| 111 |
+
logger.debug("🏠 Auth disabled - no user required")
|
| 112 |
+
return None
|
| 113 |
+
|
| 114 |
+
# Try to get user from session
|
| 115 |
+
try:
|
| 116 |
+
user = request.session.get("user")
|
| 117 |
+
if user:
|
| 118 |
+
logger.info(f"🔓 Found authenticated user: {user.get('username', 'unknown')}")
|
| 119 |
+
return user
|
| 120 |
+
else:
|
| 121 |
+
logger.debug("🔍 No user found in session")
|
| 122 |
+
return None
|
| 123 |
+
except Exception as e:
|
| 124 |
+
logger.error(f"Session access failed: {e}")
|
| 125 |
+
return None
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def get_current_user_required(request: Request) -> Dict[str, Any]:
|
| 129 |
+
"""
|
| 130 |
+
Get current user from session, raise HTTPException if not authenticated.
|
| 131 |
+
Used for endpoints that require authentication.
|
| 132 |
+
"""
|
| 133 |
+
from utils.environment import should_enable_auth
|
| 134 |
+
|
| 135 |
+
if not should_enable_auth():
|
| 136 |
+
logger.debug("🏠 Auth disabled - returning mock user")
|
| 137 |
+
return {
|
| 138 |
+
"id": "local_dev",
|
| 139 |
+
"username": "local_user",
|
| 140 |
+
"name": "Local Development User",
|
| 141 |
+
"auth_method": "local_dev"
|
| 142 |
+
}
|
| 143 |
+
|
| 144 |
+
user = get_current_user_optional(request)
|
| 145 |
+
if not user:
|
| 146 |
+
logger.warning(f"🚫 Authentication required for {request.url.path}")
|
| 147 |
+
raise HTTPException(
|
| 148 |
+
status_code=401,
|
| 149 |
+
detail={
|
| 150 |
+
"error": "Authentication required",
|
| 151 |
+
"message": "Please log in with your Hugging Face account",
|
| 152 |
+
"login_url": "/auth/login"
|
| 153 |
+
}
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
return user
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def require_auth_in_hf_spaces(request: Request) -> None:
|
| 160 |
+
"""
|
| 161 |
+
Dependency that enforces authentication only in HF Spaces.
|
| 162 |
+
Raises 401 if in HF Spaces and user is not authenticated.
|
| 163 |
+
"""
|
| 164 |
+
from utils.environment import should_enable_auth
|
| 165 |
+
|
| 166 |
+
if should_enable_auth():
|
| 167 |
+
user = get_current_user_optional(request)
|
| 168 |
+
if not user:
|
| 169 |
+
logger.warning(f"🚫 HF Spaces requires authentication for {request.url.path}")
|
| 170 |
+
raise HTTPException(
|
| 171 |
+
status_code=401,
|
| 172 |
+
detail={
|
| 173 |
+
"error": "Authentication required in Hugging Face Spaces",
|
| 174 |
+
"message": "Please log in to access this service",
|
| 175 |
+
"login_url": "/auth/login-page",
|
| 176 |
+
"reason": "This prevents abuse of OpenAI resources"
|
| 177 |
+
}
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
# Convenience aliases for common use cases
|
| 182 |
+
CurrentUser = Depends(get_current_user_required)
|
| 183 |
+
OptionalUser = Depends(get_current_user_optional)
|
| 184 |
+
RequireHFAuth = Depends(require_auth_in_hf_spaces)
|
backend/dependencies/__init__.py
DELETED
|
@@ -1,25 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Dependencies module for FastAPI dependency injection.
|
| 3 |
-
"""
|
| 4 |
-
|
| 5 |
-
from .auth import (
|
| 6 |
-
get_current_user_optional,
|
| 7 |
-
get_current_user_required,
|
| 8 |
-
get_current_user_with_bearer,
|
| 9 |
-
require_auth_in_hf_spaces,
|
| 10 |
-
CurrentUser,
|
| 11 |
-
OptionalUser,
|
| 12 |
-
APIUser,
|
| 13 |
-
RequireHFAuth
|
| 14 |
-
)
|
| 15 |
-
|
| 16 |
-
__all__ = [
|
| 17 |
-
"get_current_user_optional",
|
| 18 |
-
"get_current_user_required",
|
| 19 |
-
"get_current_user_with_bearer",
|
| 20 |
-
"require_auth_in_hf_spaces",
|
| 21 |
-
"CurrentUser",
|
| 22 |
-
"OptionalUser",
|
| 23 |
-
"APIUser",
|
| 24 |
-
"RequireHFAuth"
|
| 25 |
-
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
backend/dependencies/auth.py
DELETED
|
@@ -1,128 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Authentication Dependencies for FastAPI
|
| 3 |
-
|
| 4 |
-
This module provides authentication dependencies that can be used
|
| 5 |
-
with FastAPI's dependency injection system instead of middleware.
|
| 6 |
-
"""
|
| 7 |
-
|
| 8 |
-
import logging
|
| 9 |
-
from typing import Optional, Dict, Any
|
| 10 |
-
from fastapi import Request, HTTPException, Depends
|
| 11 |
-
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
| 12 |
-
from utils.environment import should_enable_auth, get_oauth_config, is_huggingface_space
|
| 13 |
-
|
| 14 |
-
logger = logging.getLogger(__name__)
|
| 15 |
-
|
| 16 |
-
# Optional security scheme for Bearer tokens
|
| 17 |
-
security = HTTPBearer(auto_error=False)
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
def get_current_user_optional(request: Request) -> Optional[Dict[str, Any]]:
|
| 21 |
-
"""
|
| 22 |
-
Get current user from session, but don't raise error if not found.
|
| 23 |
-
Used for endpoints where authentication is optional.
|
| 24 |
-
"""
|
| 25 |
-
if not should_enable_auth():
|
| 26 |
-
logger.debug("🏠 Auth disabled - no user required")
|
| 27 |
-
return None
|
| 28 |
-
|
| 29 |
-
# Try to get user from session
|
| 30 |
-
try:
|
| 31 |
-
user = request.session.get("user")
|
| 32 |
-
if user:
|
| 33 |
-
logger.info(f"🔓 Found authenticated user: {user.get('username', 'unknown')}")
|
| 34 |
-
return user
|
| 35 |
-
else:
|
| 36 |
-
logger.debug("🔍 No user found in session")
|
| 37 |
-
return None
|
| 38 |
-
except Exception as e:
|
| 39 |
-
logger.error(f"Session access failed: {e}")
|
| 40 |
-
return None
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
def get_current_user_required(request: Request) -> Dict[str, Any]:
|
| 44 |
-
"""
|
| 45 |
-
Get current user from session, raise HTTPException if not authenticated.
|
| 46 |
-
Used for endpoints that require authentication.
|
| 47 |
-
"""
|
| 48 |
-
if not should_enable_auth():
|
| 49 |
-
logger.debug("🏠 Auth disabled - returning mock user")
|
| 50 |
-
return {
|
| 51 |
-
"id": "local_dev",
|
| 52 |
-
"username": "local_user",
|
| 53 |
-
"name": "Local Development User",
|
| 54 |
-
"auth_method": "local_dev"
|
| 55 |
-
}
|
| 56 |
-
|
| 57 |
-
user = get_current_user_optional(request)
|
| 58 |
-
if not user:
|
| 59 |
-
logger.warning(f"🚫 Authentication required for {request.url.path}")
|
| 60 |
-
raise HTTPException(
|
| 61 |
-
status_code=401,
|
| 62 |
-
detail={
|
| 63 |
-
"error": "Authentication required",
|
| 64 |
-
"message": "Please log in with your Hugging Face account",
|
| 65 |
-
"login_url": "/auth/login"
|
| 66 |
-
}
|
| 67 |
-
)
|
| 68 |
-
|
| 69 |
-
return user
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
def get_current_user_with_bearer(
|
| 73 |
-
request: Request,
|
| 74 |
-
credentials: Optional[HTTPAuthorizationCredentials] = Depends(security)
|
| 75 |
-
) -> Optional[Dict[str, Any]]:
|
| 76 |
-
"""
|
| 77 |
-
Get current user from session or Bearer token.
|
| 78 |
-
Used for API endpoints that might accept both session and token auth.
|
| 79 |
-
"""
|
| 80 |
-
# First try session authentication
|
| 81 |
-
user = get_current_user_optional(request)
|
| 82 |
-
if user:
|
| 83 |
-
return user
|
| 84 |
-
|
| 85 |
-
# If no session user, try Bearer token (for API access)
|
| 86 |
-
if credentials and is_huggingface_space():
|
| 87 |
-
# In a full implementation, validate this token with HF API
|
| 88 |
-
# For now, assume it's valid if present in HF environment
|
| 89 |
-
logger.info("🔑 User authenticated via Bearer token")
|
| 90 |
-
return {
|
| 91 |
-
"id": "bearer_auth",
|
| 92 |
-
"username": "api_user",
|
| 93 |
-
"name": "API User",
|
| 94 |
-
"auth_method": "bearer_token",
|
| 95 |
-
"token": credentials.credentials
|
| 96 |
-
}
|
| 97 |
-
|
| 98 |
-
return None
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
# Convenience aliases for common use cases
|
| 102 |
-
CurrentUser = Depends(get_current_user_required)
|
| 103 |
-
OptionalUser = Depends(get_current_user_optional)
|
| 104 |
-
APIUser = Depends(get_current_user_with_bearer)
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
def require_auth_in_hf_spaces(request: Request) -> None:
|
| 108 |
-
"""
|
| 109 |
-
Dependency that enforces authentication only in HF Spaces.
|
| 110 |
-
Raises 401 if in HF Spaces and user is not authenticated.
|
| 111 |
-
"""
|
| 112 |
-
if should_enable_auth():
|
| 113 |
-
user = get_current_user_optional(request)
|
| 114 |
-
if not user:
|
| 115 |
-
logger.warning(f"🚫 HF Spaces requires authentication for {request.url.path}")
|
| 116 |
-
raise HTTPException(
|
| 117 |
-
status_code=401,
|
| 118 |
-
detail={
|
| 119 |
-
"error": "Authentication required in Hugging Face Spaces",
|
| 120 |
-
"message": "Please log in to access this service",
|
| 121 |
-
"login_url": "/auth/login-page",
|
| 122 |
-
"reason": "This prevents abuse of OpenAI resources"
|
| 123 |
-
}
|
| 124 |
-
)
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
# Dependency alias for route protection
|
| 128 |
-
RequireHFAuth = Depends(require_auth_in_hf_spaces)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|