Source code for app.routers.depends

from typing import Generator

from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from jose import jwt
from pydantic import ValidationError
from sqlalchemy.orm import Session

from app import crud, models, schemas
from app.core import security
from app.core.config import settings
from app.db.session import SessionLocal

login_url = f"{settings.api_version}/login/access-token"
reusable_oauth2 = OAuth2PasswordBearer(tokenUrl=login_url)


[docs]def get_db() -> Generator: """ Get the database in a context so we can then close it. """ try: db = SessionLocal() yield db finally: db.close()
[docs]def get_current_user( db: Session = Depends(get_db), token: str = Depends(reusable_oauth2) ) -> models.User: """ Get the current user (via the token from the jwt) And fail if not authenticated or expired. """ try: payload = jwt.decode( token, settings.secret_key, algorithms=[security.ALGORITHM] ) token_data = schemas.TokenPayload(**payload) except (jwt.JWTError, ValidationError): raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Could not validate credentials", ) user = crud.user.get(db, id=token_data.sub) if not user: raise HTTPException(status_code=404, detail="User not found") return user
[docs]def get_current_active_user( current_user: models.User = Depends(get_current_user), ) -> models.User: """ Get the currently active user. """ if not crud.user.is_active(current_user): raise HTTPException(status_code=400, detail="Inactive user") return current_user
[docs]def get_current_active_superuser( current_user: models.User = Depends(get_current_user), ) -> models.User: """ Get the currently active superuser. """ if not crud.user.is_superuser(current_user): raise HTTPException( status_code=400, detail="The user doesn't have enough privileges" ) return current_user

Last update: Mar 10, 2024