Reputation: 103
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!
Upvotes: 0
Views: 409
Reputation: 193
You have a public schema (accessible for everyone). Each tenant must have its own schema. The private data should always be stored in their own schema. After ensuring this, you have a search path that django Django-tenants library manages for you.
This way, the search path is (host schema, public schema). If the table does not exist in host schema, the search will be made in the public schema. This way, you can have tenant based structure only in tenant schemas and public structures (for everyone) in the public schema.
I hope this made the procedure clearer.
Upvotes: 0