Spaces:
Runtime error
Runtime error
Download core/auth.py from Quratulain1/Deploy-Backend: direct link, hf CLI and curl.
- Browser
- Download file 6.1 kB
-
https://huggingface.co/spaces/Quratulain1/Deploy-Backend/resolve/main/core/auth.py
- Command line
-
hf download hf://spaces/Quratulain1/Deploy-Backend/core/auth.py
-
curl -L -o auth.py https://huggingface.co/spaces/Quratulain1/Deploy-Backend/resolve/main/core/auth.py
6.1 kB
| from fastapi import Depends, HTTPException, status | |
| from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials | |
| import logging | |
| import jwt | |
| from jwt.jwk import PyJWK | |
| from core.config import settings | |
| from core.db import async_session_maker | |
| from sqlalchemy import text | |
| import json | |
| logger = logging.getLogger(__name__) | |
| # Use HTTPBearer for token validation | |
| bearer_scheme = HTTPBearer(auto_error=True) | |
| # Cache for EdDSA public keys from Better Auth | |
| _jwks_cache = None | |
| async def get_jwks() -> dict: | |
| """Fetch EdDSA public keys from Better Auth's jwks table.""" | |
| global _jwks_cache | |
| if _jwks_cache is not None: | |
| return _jwks_cache | |
| try: | |
| async with async_session_maker() as session: | |
| result = await session.execute(text('SELECT id, "publicKey" FROM jwks')) | |
| keys = result.fetchall() | |
| jwks = {} | |
| for key_id, public_key_json in keys: | |
| jwks[key_id] = json.loads(public_key_json) | |
| _jwks_cache = jwks | |
| logger.info(f"[AUTH] Loaded {len(jwks)} EdDSA public keys from database") | |
| return jwks | |
| except Exception as e: | |
| logger.error(f"[AUTH] Failed to load JWKS: {e}") | |
| return {} | |
| async def get_current_user( | |
| credentials: HTTPAuthorizationCredentials = Depends(bearer_scheme) | |
| ) -> str: | |
| """ | |
| Validate Better Auth JWT using EdDSA (asymmetric cryptography). | |
| Better Auth generates stateless JWTs signed with EdDSA using Ed25519 keys. | |
| This function verifies the JWT signature using the public key from the database. | |
| IMPORTANT: This is stateless JWT verification - no session table needed. | |
| """ | |
| token = credentials.credentials | |
| logger.info(f"[AUTH] Received Bearer token (length: {len(token)}, starts with: {token[:20]}...)") | |
| try: | |
| # First, decode the JWT header to get the key ID (kid) | |
| import base64 | |
| header_b64 = token.split('.')[0] | |
| header_b64 += '=' * (4 - len(header_b64) % 4) | |
| header = json.loads(base64.urlsafe_b64decode(header_b64)) | |
| logger.info(f"[AUTH] JWT Header: {header}") | |
| kid = header.get('kid') | |
| if not kid: | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Missing key ID in JWT header", | |
| headers={"WWW-Authenticate": "Bearer"}, | |
| ) | |
| # Get the public key for this kid | |
| jwks = await get_jwks() | |
| if kid not in jwks: | |
| logger.error(f"[AUTH] Unknown key ID: {kid}") | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Unknown signing key", | |
| headers={"WWW-Authenticate": "Bearer"}, | |
| ) | |
| public_key_jwk = jwks[kid] | |
| logger.info(f"[AUTH] Using EdDSA public key for kid: {kid}") | |
| # Convert JWK to PyJWT key format | |
| public_key = PyJWK(public_key_jwk).key | |
| # Verify JWT signature using EdDSA public key | |
| payload = jwt.decode( | |
| token, | |
| public_key, | |
| algorithms=["EdDSA"], | |
| options={ | |
| "verify_exp": True, | |
| "verify_iat": True, | |
| "verify_nbf": True, | |
| "verify_aud": False, | |
| "verify_iss": False, | |
| } | |
| ) | |
| logger.info(f"[AUTH] Successfully decoded Better Auth JWT payload: {payload}") | |
| # Extract user ID from Better Auth JWT payload | |
| user_id = payload.get("sub") or payload.get("id") | |
| if not user_id: | |
| logger.warning("[AUTH] No user ID found in Better Auth JWT payload") | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Invalid token: no user identifier found", | |
| headers={"WWW-Authenticate": "Bearer"}, | |
| ) | |
| logger.info(f"[AUTH] Validated Better Auth EdDSA JWT for user: {user_id}") | |
| # Create user record if doesn't exist (for data isolation) | |
| await ensure_user_exists(user_id) | |
| return user_id | |
| except jwt.PyJWTError as e: | |
| logger.error(f"[AUTH] Better Auth JWT validation failed: {str(e)}") | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Invalid or expired Better Auth token", | |
| headers={"WWW-Authenticate": "Bearer"}, | |
| ) | |
| except HTTPException: | |
| raise | |
| except Exception as e: | |
| logger.error(f"[AUTH] Unexpected error during Better Auth JWT validation: {str(e)}") | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Authentication failed", | |
| headers={"WWW-Authenticate": "Bearer"}, | |
| ) | |
| async def ensure_user_exists(user_id: str) -> None: | |
| """Create user in database if they don't exist.""" | |
| try: | |
| from core.db import async_session_maker | |
| async with async_session_maker() as session: | |
| # Check if user exists | |
| result = await session.execute( | |
| text('SELECT 1 FROM "user" WHERE id = :user_id LIMIT 1'), | |
| {"user_id": user_id} | |
| ) | |
| user_exists = result.fetchone() is not None | |
| if not user_exists: | |
| # Create user record for data isolation | |
| await session.execute( | |
| text(''' | |
| INSERT INTO "user" (id, email, "emailVerified", name, "createdAt", "updatedAt") | |
| VALUES (:id, :email, false, :name, NOW(), NOW()) | |
| ON CONFLICT (id) DO NOTHING | |
| '''), | |
| { | |
| "id": user_id, | |
| "email": f"user_{user_id[:8]}@example.com", | |
| "name": "User" | |
| } | |
| ) | |
| await session.commit() | |
| logger.info(f"[AUTH] Created user record: {user_id}") | |
| except Exception as e: | |
| logger.error(f"[AUTH] Error ensuring user exists: {e}") | |
| # Continue anyway - this is not critical for auth validation | |