Spaces:
Sleeping
Sleeping
| from fastapi import Depends, HTTPException, status | |
| from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer | |
| from jose import JWTError, jwt | |
| from .config import get_settings | |
| from .services.users import get_user_by_id, serialize_user | |
| security = HTTPBearer() | |
| async def get_current_user(credentials: HTTPAuthorizationCredentials = Depends(security)): | |
| token = credentials.credentials | |
| settings = get_settings() | |
| try: | |
| payload = jwt.decode(token, settings.jwt_secret_key, algorithms=[settings.jwt_algorithm]) | |
| except JWTError as exc: # pragma: no cover - error path | |
| raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Could not validate credentials") from exc | |
| user_id: str = payload.get("sub") | |
| if user_id is None: | |
| raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token payload") | |
| user_doc = await get_user_by_id(user_id) | |
| if user_doc is None: | |
| raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="User not found") | |
| return serialize_user(user_doc) | |