41 lines
1.2 KiB
Python
41 lines
1.2 KiB
Python
from typing import Generator
|
|
|
|
from fastapi import Depends, HTTPException, status
|
|
from fastapi.security import OAuth2PasswordBearer
|
|
from jose import JWTError, jwt
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.core.config import settings
|
|
from app.db.session import SessionLocal
|
|
from app.models.user import User
|
|
|
|
|
|
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/auth/login")
|
|
|
|
|
|
def get_db() -> Generator[Session, None, None]:
|
|
db = SessionLocal()
|
|
try:
|
|
yield db
|
|
finally:
|
|
db.close()
|
|
|
|
|
|
def get_current_user(token: str = Depends(oauth2_scheme), db: Session = Depends(get_db)) -> User:
|
|
credentials_exception = HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Could not validate credentials",
|
|
headers={"WWW-Authenticate": "Bearer"},
|
|
)
|
|
try:
|
|
payload = jwt.decode(token, settings.secret_key, algorithms=[settings.jwt_algorithm])
|
|
username: str | None = payload.get("sub")
|
|
if username is None:
|
|
raise credentials_exception
|
|
except JWTError as exc:
|
|
raise credentials_exception from exc
|
|
user = db.query(User).filter(User.username == username).first()
|
|
if not user:
|
|
raise credentials_exception
|
|
return user
|