Download core/auth/auth.py from Kyrlos11/nniback: direct link, hf CLI and curl.
- Browser
- Download file 2 kB
-
https://huggingface.co/spaces/Kyrlos11/nniback/resolve/main/core/auth/auth.py
- Command line
-
hf download hf://spaces/Kyrlos11/nniback/core/auth/auth.py
-
curl -L -o auth.py https://huggingface.co/spaces/Kyrlos11/nniback/resolve/main/core/auth/auth.py
2 kB
| from fastapi import HTTPException, Depends, Security, Request | |
| from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials | |
| from typing import Optional | |
| from core.services.supabase import DBConnection | |
| from core.utils.logger import logger | |
| security = HTTPBearer(auto_error=False) # Don't auto-error, we handle both API key and Bearer | |
| async def get_current_user(request: Request, credentials: Optional[HTTPAuthorizationCredentials] = Security(security)) -> dict: | |
| """ | |
| Authenticate user via either X-API-Key header or Bearer token. | |
| Supports both authentication methods for all endpoints. | |
| """ | |
| from core.utils.auth_utils import verify_and_get_user_id_from_jwt | |
| try: | |
| user_id = await verify_and_get_user_id_from_jwt(request) | |
| # Get token from credentials if available (for backwards compatibility) | |
| token = credentials.credentials if credentials else None | |
| return {"user_id": user_id, "token": token} | |
| except Exception as e: | |
| logger.error(f"Auth failed: {e}") | |
| raise HTTPException(status_code=401, detail="Invalid authentication") | |
| def verify_role(required_role: str): | |
| async def role_checker(user: dict = Depends(get_current_user)) -> dict: | |
| db = DBConnection() | |
| client = await db.client | |
| result = await client.table('user_roles').select('role').eq('user_id', user['user_id']).execute() | |
| if not result.data or len(result.data) == 0: | |
| raise HTTPException(status_code=403, detail="No role assigned") | |
| user_role = result.data[0]['role'] | |
| role_hierarchy = {'user': 0, 'admin': 1, 'super_admin': 2} | |
| if role_hierarchy.get(user_role, -1) < role_hierarchy.get(required_role, 999): | |
| raise HTTPException(status_code=403, detail=f"Requires {required_role} role") | |
| user['role'] = user_role | |
| return user | |
| return role_checker | |
| require_admin = verify_role('admin') | |
| require_super_admin = verify_role('super_admin') |