I'm building a multi-tenant application using Django with django-tenant and django-tenant-users for handling tenants and user authentication. However, I'm struggling to find the best approach to prevent users from one tenant accessing data or functionality of another tenant.
I've explored custom middleware, Django's permission system, and user profile models, but haven't found clear guidance on enforcing tenant isolation within the Django framework.
Middleware.py
from django.core.exceptions import PermissionDenied
class TenantAuthMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
if request.user.is_authenticated:
if request.tenant not in request.user.tenants.all():
raise PermissionDenied
response = self.get_response(request)
return response
For those familiar with django-tenant and django-tenant-users, how do you ensure that users from one tenant cannot access data or features belonging to another tenant?
Thank you!