43 lines
1.4 KiB
Python
43 lines
1.4 KiB
Python
from fastapi import Depends, HTTPException, status
|
|
from fastapi.security import OAuth2PasswordBearer
|
|
from jose import JWTError
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.auth import decode_token
|
|
from app.db import SessionLocal
|
|
from app.models import User, UserRole
|
|
|
|
|
|
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/auth/login")
|
|
|
|
|
|
def get_db():
|
|
db = SessionLocal()
|
|
try:
|
|
yield db
|
|
finally:
|
|
db.close()
|
|
|
|
|
|
def get_current_user(token: str = Depends(oauth2_scheme), db: Session = Depends(get_db)) -> User:
|
|
try:
|
|
payload = decode_token(token, "access")
|
|
if payload.get("type") != "access":
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
|
|
user_id = int(payload.get("sub"))
|
|
except (JWTError, ValueError):
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
|
|
|
|
user = db.get(User, user_id)
|
|
if not user:
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="User not found")
|
|
if not user.is_active:
|
|
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="User inactive")
|
|
return user
|
|
|
|
|
|
def require_admin(user: User = Depends(get_current_user)) -> User:
|
|
if user.role != UserRole.admin:
|
|
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Admin only")
|
|
return user
|