backend / app /core /async_dependencies.py
Monteeq CI
๐Ÿš€ Initial deployment of Monteeq backend
3533fb9
Raw History Blame Contribute Delete
1.34 kB
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from jose import JWTError, jwt
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.future import select
from app.core.config import SECRET_KEY, ALGORITHM
from app.db.async_session import get_async_db
from app.models.models import User
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
async def get_async_current_user(
db: AsyncSession = Depends(get_async_db),
token: str = Depends(oauth2_scheme)
):
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
username: str = payload.get("sub")
if username is None:
raise credentials_exception
except JWTError:
raise credentials_exception
result = await db.execute(select(User).filter(User.username == username))
user = result.scalar_one_or_none()
if not user:
raise credentials_exception
if not user.is_active:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Account is deactivated"
)
return user