initial commit
This commit is contained in:
@@ -0,0 +1,57 @@
|
||||
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
|
||||
|
||||
token_tv = payload.get("tv", 0)
|
||||
user_tv = getattr(user, "token_version", 0)
|
||||
if token_tv != user_tv:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Token has been invalidated. Please log in again.",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
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
|
||||
Reference in New Issue
Block a user