Files
MOHPortalTest-AllAgents-All…/qwen/python/merchants_of_hope/services/tenant_service.py
2025-10-24 16:29:40 -05:00

49 lines
1.5 KiB
Python

"""
Multi-tenant service for managing tenant-specific operations
"""
from typing import Optional
from fastapi import Request
from sqlalchemy.orm import Session
from ..models import Tenant
from ..config.settings import settings
def get_current_tenant_id(request: Request) -> Optional[int]:
"""
Get the current tenant ID from the request
"""
return getattr(request.state, 'tenant_id', None)
def verify_tenant_access(request: Request, db: Session, resource_tenant_id: int) -> bool:
"""
Verify that the current tenant has access to a resource
"""
if not settings.MULTI_TENANT_ENABLED:
return True # If multi-tenancy is disabled, allow access
current_tenant_id = get_current_tenant_id(request)
return current_tenant_id == resource_tenant_id
def check_tenant_isolation(request: Request, db: Session, model_class, id: int) -> bool:
"""
Check if a specific instance of a model belongs to the current tenant
"""
if not settings.MULTI_TENANT_ENABLED:
return True
current_tenant_id = get_current_tenant_id(request)
# Assuming the model has a tenant_id attribute
instance = db.query(model_class).filter(model_class.id == id).first()
if not instance:
return False
# This is a generic approach - in practice you'd need to handle specific model types
if hasattr(instance, 'tenant_id'):
return instance.tenant_id == current_tenant_id
else:
# For models that aren't tenant-specific, allow access
return True