Spaces:
No application file
No application file
| from fastapi import Depends, HTTPException, status | |
| from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials | |
| from typing import Optional | |
| from utils.jwt import verify_token | |
| from schemas.user import UserRead | |
| import uuid | |
| security = HTTPBearer() | |
| def get_current_user(credentials: HTTPAuthorizationCredentials = Depends(security)): | |
| """ | |
| Dependency to get the current user from the JWT token | |
| """ | |
| token = credentials.credentials | |
| payload = verify_token(token) | |
| if payload is None: | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Could not validate credentials", | |
| headers={"WWW-Authenticate": "Bearer"}, | |
| ) | |
| user_id_str = payload.get("sub") | |
| if user_id_str is None: | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Could not validate credentials", | |
| headers={"WWW-Authenticate": "Bearer"}, | |
| ) | |
| try: | |
| user_id = uuid.UUID(user_id_str) | |
| except ValueError: | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Invalid user ID in token", | |
| headers={"WWW-Authenticate": "Bearer"}, | |
| ) | |
| # Create a UserRead object with the user ID | |
| # In a real implementation, you would fetch the user from the database | |
| user = UserRead(id=user_id, email="", created_at=None, updated_at=None) | |
| return user |