| """ |
| FastAPI dependencies for authentication and database access |
| """ |
| from fastapi import Depends, HTTPException, status |
| from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials |
| from sqlalchemy.orm import Session |
| from app.database import get_db |
| from app.models import User |
| from app.services.auth_service import decode_access_token |
|
|
| |
| security = HTTPBearer() |
|
|
|
|
| async def get_current_user( |
| credentials: HTTPAuthorizationCredentials = Depends(security), |
| db: Session = Depends(get_db) |
| ) -> User: |
| """ |
| Dependency to get the current authenticated user from JWT token |
| |
| Raises: |
| HTTPException 401: If token is invalid or user not found |
| """ |
| token = credentials.credentials |
| |
| |
| payload = decode_access_token(token) |
| if payload is None: |
| raise HTTPException( |
| status_code=status.HTTP_401_UNAUTHORIZED, |
| detail="Invalid or expired token", |
| headers={"WWW-Authenticate": "Bearer"} |
| ) |
| |
| |
| user_id = payload.get("sub") |
| if user_id is None: |
| raise HTTPException( |
| status_code=status.HTTP_401_UNAUTHORIZED, |
| detail="Invalid token payload", |
| headers={"WWW-Authenticate": "Bearer"} |
| ) |
| |
| |
| user = db.query(User).filter(User.id == user_id).first() |
| if user is None: |
| raise HTTPException( |
| status_code=status.HTTP_401_UNAUTHORIZED, |
| detail="User not found", |
| headers={"WWW-Authenticate": "Bearer"} |
| ) |
| |
| return user |
|
|