83 lines
2.2 KiB
Python
83 lines
2.2 KiB
Python
"""Shared dependencies for FastAPI dependency injection."""
|
|
|
|
from typing import Generator, Optional
|
|
from fastapi import Depends, HTTPException, status
|
|
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
|
from sqlalchemy.orm import Session
|
|
from jose import JWTError, jwt
|
|
|
|
from app.db.session import SessionLocal
|
|
from app.config import settings
|
|
from app.core.security import decode_access_token
|
|
from app import models, crud
|
|
|
|
|
|
# Database dependency
|
|
def get_db() -> Generator[Session, None, None]:
|
|
"""
|
|
Dependency that provides a database session.
|
|
Automatically closes the session after the request.
|
|
"""
|
|
db = SessionLocal()
|
|
try:
|
|
yield db
|
|
finally:
|
|
db.close()
|
|
|
|
|
|
# Security
|
|
security = HTTPBearer()
|
|
|
|
|
|
def get_current_user(
|
|
credentials: HTTPAuthorizationCredentials = Depends(security),
|
|
db: Session = Depends(get_db)
|
|
) -> models.User:
|
|
"""
|
|
Dependency that validates JWT token and returns current user.
|
|
Raises HTTPException if token is invalid or user not found.
|
|
"""
|
|
credentials_exception = HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Could not validate credentials",
|
|
headers={"WWW-Authenticate": "Bearer"},
|
|
)
|
|
|
|
try:
|
|
payload = decode_access_token(credentials.credentials)
|
|
user_id: str = payload.get("sub")
|
|
if user_id is None:
|
|
raise credentials_exception
|
|
except JWTError:
|
|
raise credentials_exception
|
|
|
|
user = crud.user.get(db, id=user_id)
|
|
if user is None:
|
|
raise credentials_exception
|
|
|
|
if not user.is_active:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_403_FORBIDDEN,
|
|
detail="Inactive user"
|
|
)
|
|
|
|
return user
|
|
|
|
|
|
def get_current_active_superuser(
|
|
current_user: models.User = Depends(get_current_user)
|
|
) -> models.User:
|
|
"""
|
|
Dependency that requires the current user to be a superuser.
|
|
"""
|
|
if not current_user.is_superuser:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_403_FORBIDDEN,
|
|
detail="Not enough permissions"
|
|
)
|
|
return current_user
|
|
|
|
|
|
# Alias for backward compatibility
|
|
get_current_superuser = get_current_active_superuser
|