Spaces:
Sleeping
Sleeping
Download api/endpoints/auth.py from Quratulain1/backend-chatbot: direct link, hf CLI and curl.
- Browser
- Download file 8.5 kB
-
https://huggingface.co/spaces/Quratulain1/backend-chatbot/resolve/main/api/endpoints/auth.py
- Command line
-
hf download hf://spaces/Quratulain1/backend-chatbot/api/endpoints/auth.py
-
curl -L -o auth.py https://huggingface.co/spaces/Quratulain1/backend-chatbot/resolve/main/api/endpoints/auth.py
8.5 kB
| """ | |
| Authentication Endpoints for JWT Token Management | |
| Implements a secure JWT refresh token flow: | |
| - Short-lived access tokens (15 minutes) | |
| - Long-lived refresh tokens (7 days) | |
| - Token refresh endpoint | |
| - EdDSA (Ed25519) signing algorithm | |
| """ | |
| from fastapi import APIRouter, HTTPException, status, Depends | |
| from pydantic import BaseModel, EmailStr | |
| from datetime import datetime, timedelta, timezone | |
| from typing import Optional | |
| import jwt | |
| import logging | |
| from cryptography.hazmat.primitives.asymmetric import ed25519 | |
| from cryptography.hazmat.primitives import serialization | |
| from core.db import async_session_maker | |
| from sqlalchemy import text | |
| import json | |
| logger = logging.getLogger(__name__) | |
| router = APIRouter() | |
| # Request/Response Models | |
| class LoginRequest(BaseModel): | |
| email: EmailStr | |
| password: str | |
| class TokenResponse(BaseModel): | |
| access_token: str | |
| refresh_token: str | |
| token_type: str = "bearer" | |
| expires_in: int # seconds until access token expires | |
| class RefreshRequest(BaseModel): | |
| refresh_token: str | |
| # Token Configuration | |
| ACCESS_TOKEN_EXPIRE_MINUTES = 15 # Short-lived access token | |
| REFRESH_TOKEN_EXPIRE_DAYS = 7 # Long-lived refresh token | |
| TEST_KEY_ID = "test-key-001" | |
| async def get_signing_key(): | |
| """Get the EdDSA private key from database for signing tokens.""" | |
| try: | |
| async with async_session_maker() as session: | |
| result = await session.execute( | |
| text('SELECT "privateKey" FROM jwks WHERE id = :kid LIMIT 1'), | |
| {"kid": TEST_KEY_ID} | |
| ) | |
| row = result.fetchone() | |
| if not row: | |
| raise HTTPException( | |
| status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, | |
| detail="Signing key not found in database" | |
| ) | |
| private_key_pem = row[0] | |
| # Load the private key from PEM format | |
| private_key = serialization.load_pem_private_key( | |
| private_key_pem.encode('utf-8'), | |
| password=None | |
| ) | |
| return private_key | |
| except Exception as e: | |
| logger.error(f"[AUTH] Failed to load signing key: {e}") | |
| raise HTTPException( | |
| status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, | |
| detail="Failed to load signing key" | |
| ) | |
| def create_access_token(user_id: str, private_key) -> str: | |
| """Create a short-lived access token.""" | |
| now = datetime.now(timezone.utc) | |
| expire = now + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) | |
| payload = { | |
| "sub": user_id, | |
| "type": "access", # Token type identifier | |
| "exp": expire, | |
| "iat": now, | |
| "nbf": now | |
| } | |
| # Convert private key to PEM for PyJWT | |
| private_pem = private_key.private_bytes( | |
| encoding=serialization.Encoding.PEM, | |
| format=serialization.PrivateFormat.PKCS8, | |
| encryption_algorithm=serialization.NoEncryption() | |
| ) | |
| token = jwt.encode( | |
| payload, | |
| private_pem, | |
| algorithm="EdDSA", | |
| headers={"kid": TEST_KEY_ID} | |
| ) | |
| return token | |
| def create_refresh_token(user_id: str, private_key) -> str: | |
| """Create a long-lived refresh token.""" | |
| now = datetime.now(timezone.utc) | |
| expire = now + timedelta(days=REFRESH_TOKEN_EXPIRE_DAYS) | |
| payload = { | |
| "sub": user_id, | |
| "type": "refresh", # Token type identifier | |
| "exp": expire, | |
| "iat": now, | |
| "nbf": now | |
| } | |
| # Convert private key to PEM for PyJWT | |
| private_pem = private_key.private_bytes( | |
| encoding=serialization.Encoding.PEM, | |
| format=serialization.PrivateFormat.PKCS8, | |
| encryption_algorithm=serialization.NoEncryption() | |
| ) | |
| token = jwt.encode( | |
| payload, | |
| private_pem, | |
| algorithm="EdDSA", | |
| headers={"kid": TEST_KEY_ID} | |
| ) | |
| return token | |
| async def login(request: LoginRequest): | |
| """ | |
| Login endpoint that returns both access and refresh tokens. | |
| For development/testing, this accepts any email/password combination. | |
| In production, you would validate credentials against a user database. | |
| """ | |
| try: | |
| # Extract user_id from email (part before @) | |
| user_id = request.email.split('@')[0] | |
| # Get signing key | |
| private_key = await get_signing_key() | |
| # Generate tokens | |
| access_token = create_access_token(user_id, private_key) | |
| refresh_token = create_refresh_token(user_id, private_key) | |
| logger.info(f"[AUTH] Generated tokens for user: {user_id}") | |
| return TokenResponse( | |
| access_token=access_token, | |
| refresh_token=refresh_token, | |
| token_type="bearer", | |
| expires_in=ACCESS_TOKEN_EXPIRE_MINUTES * 60 | |
| ) | |
| except HTTPException: | |
| raise | |
| except Exception as e: | |
| logger.error(f"[AUTH] Login failed: {e}") | |
| raise HTTPException( | |
| status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, | |
| detail="Login failed" | |
| ) | |
| async def refresh_tokens(request: RefreshRequest): | |
| """ | |
| Refresh endpoint that validates a refresh token and returns new tokens. | |
| This endpoint: | |
| 1. Validates the refresh token | |
| 2. Checks that it's actually a refresh token (not an access token) | |
| 3. Generates new access and refresh tokens | |
| """ | |
| try: | |
| # Get public key for validation | |
| async with async_session_maker() as session: | |
| result = await session.execute( | |
| text('SELECT "publicKey" FROM jwks WHERE id = :kid LIMIT 1'), | |
| {"kid": TEST_KEY_ID} | |
| ) | |
| row = result.fetchone() | |
| if not row: | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Invalid refresh token" | |
| ) | |
| public_key_jwk = json.loads(row[0]) | |
| # Validate refresh token | |
| from jwt import PyJWK | |
| public_key = PyJWK(public_key_jwk).key | |
| try: | |
| payload = jwt.decode( | |
| request.refresh_token, | |
| public_key, | |
| algorithms=["EdDSA"], | |
| options={ | |
| "verify_exp": True, | |
| "verify_iat": True, | |
| "verify_nbf": True, | |
| } | |
| ) | |
| except jwt.ExpiredSignatureError: | |
| logger.warning("[AUTH] Refresh token has expired") | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Refresh token has expired. Please login again." | |
| ) | |
| except jwt.PyJWTError as e: | |
| logger.error(f"[AUTH] Invalid refresh token: {e}") | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Invalid refresh token" | |
| ) | |
| # Verify this is actually a refresh token | |
| if payload.get("type") != "refresh": | |
| logger.warning("[AUTH] Attempted to refresh with non-refresh token") | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Invalid token type. Expected refresh token." | |
| ) | |
| # Extract user_id | |
| user_id = payload.get("sub") | |
| if not user_id: | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Invalid token: no user identifier" | |
| ) | |
| # Get signing key | |
| private_key = await get_signing_key() | |
| # Generate new tokens | |
| new_access_token = create_access_token(user_id, private_key) | |
| new_refresh_token = create_refresh_token(user_id, private_key) | |
| logger.info(f"[AUTH] Refreshed tokens for user: {user_id}") | |
| return TokenResponse( | |
| access_token=new_access_token, | |
| refresh_token=new_refresh_token, | |
| token_type="bearer", | |
| expires_in=ACCESS_TOKEN_EXPIRE_MINUTES * 60 | |
| ) | |
| except HTTPException: | |
| raise | |
| except Exception as e: | |
| logger.error(f"[AUTH] Token refresh failed: {e}") | |
| raise HTTPException( | |
| status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, | |
| detail="Token refresh failed" | |
| ) | |
| async def auth_health(): | |
| """Health check endpoint for auth service.""" | |
| return {"status": "ok", "service": "auth"} | |