phase0-multi-tenant-rls-rbac
This commit is contained in:
1 parent
f9c8bda6e0
commit
7b1941fdaf
3 files changed
+97
-2
No files matched your search
@@ -12,6 +12,30 @@ from fastapi import Depends, HTTPException, status, Request
|
||||
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
||||
from .config import SECRET_KEY, ALGORITHM, ACCESS_TOKEN_EXPIRE_MINUTES
|
||||
|
||||
|
||||
# Phase0: 5-level RBAC hierarchy
|
||||
ROLE_HIERARCHY = {
|
||||
"super_admin": 100,
|
||||
"admin": 80,
|
||||
"developer": 50,
|
||||
"user": 30,
|
||||
"guest": 10,
|
||||
}
|
||||
|
||||
def has_role(user_role: str, required: str) -> bool:
|
||||
return ROLE_HIERARCHY.get(user_role, 0) >= ROLE_HIERARCHY.get(required, 0)
|
||||
|
||||
|
||||
async def get_current_tenant(
|
||||
credentials: HTTPAuthorizationCredentials = Depends(security),
|
||||
) -> Optional[str]:
|
||||
"""Phase0: Extract tenant_id from JWT token"""
|
||||
try:
|
||||
payload = jwt.decode(credentials.credentials, SECRET_KEY, algorithms=[ALGORITHM])
|
||||
return payload.get("tenant_id")
|
||||
except JWTError:
|
||||
return None
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
security = HTTPBearer()
|
||||
@@ -35,8 +59,10 @@ def verify_password(plain_password: str, hashed_password: str) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -> str:
|
||||
def create_access_token(data: dict, expires_delta: Optional[timedelta] = None, tenant_id: str = None) -> str:
|
||||
to_encode = data.copy()
|
||||
if tenant_id:
|
||||
to_encode["tenant_id"] = tenant_id
|
||||
expire = datetime.utcnow() + (expires_delta or timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES))
|
||||
to_encode.update({"exp": expire})
|
||||
return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
|
||||
|
||||
Reference in new issue
Block a user