49 lines
1.5 KiB
Python
49 lines
1.5 KiB
Python
from fastapi import Depends, HTTPException, status
|
|
from fastapi.security import OAuth2PasswordBearer
|
|
from jose import JWTError
|
|
from sqlalchemy.orm import Session
|
|
from .db import get_db
|
|
from .security import decode_token
|
|
from ..models.masters import User
|
|
from ..services.permissions import Role
|
|
|
|
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/auth/login")
|
|
|
|
|
|
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 = decode_token(token)
|
|
sub = payload.get("sub")
|
|
if sub is None:
|
|
raise credentials_exception
|
|
user_id = int(sub)
|
|
except (JWTError, ValueError, TypeError):
|
|
raise credentials_exception
|
|
|
|
user = db.query(User).filter(User.id == user_id).first()
|
|
if user is None or not user.is_active:
|
|
raise credentials_exception
|
|
return user
|
|
|
|
|
|
def require_roles(*roles: Role | str):
|
|
allowed = {r.value if isinstance(r, Role) else r for r in roles}
|
|
|
|
def _dependency(current_user: User = Depends(get_current_user)) -> User:
|
|
if current_user.role not in allowed:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_403_FORBIDDEN,
|
|
detail="Insufficient permissions for this action.",
|
|
)
|
|
return current_user
|
|
|
|
return _dependency
|