fix: Use request.tenant instead of request.user.tenant for user validation
Platform-level users (owners) may have tenant=None on their user record but still access tenant subdomains. The _get_valid_user method now uses request.tenant (from django-tenants middleware) which is set based on the subdomain being accessed, not the user's tenant FK. This fixes 400 Bad Request errors when platform users try to create resources with staff assignments. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
@@ -223,10 +223,14 @@ class ResourceSerializer(serializers.ModelSerializer):
|
|||||||
|
|
||||||
def _get_valid_user(self, user_id):
|
def _get_valid_user(self, user_id):
|
||||||
"""
|
"""
|
||||||
Get a user by ID, validating they belong to the same tenant as the request user.
|
Get a user by ID, validating they belong to the same tenant as the request.
|
||||||
Returns None if user doesn't exist or doesn't belong to the same tenant.
|
Returns None if user doesn't exist or doesn't belong to the same tenant.
|
||||||
|
|
||||||
CRITICAL: This prevents cross-tenant user linking (multi-tenancy security).
|
CRITICAL: This prevents cross-tenant user linking (multi-tenancy security).
|
||||||
|
|
||||||
|
Uses request.tenant (from django-tenants middleware) rather than request.user.tenant
|
||||||
|
because platform-level users (owners) may have tenant=None on their user record
|
||||||
|
but still access tenant subdomains.
|
||||||
"""
|
"""
|
||||||
if not user_id:
|
if not user_id:
|
||||||
return None
|
return None
|
||||||
@@ -235,10 +239,16 @@ class ResourceSerializer(serializers.ModelSerializer):
|
|||||||
if not request or not request.user.is_authenticated:
|
if not request or not request.user.is_authenticated:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
# Use request.tenant (from django-tenants middleware) - this is set based on
|
||||||
|
# the subdomain being accessed, not the user's tenant FK
|
||||||
|
tenant = getattr(request, 'tenant', None)
|
||||||
|
if not tenant:
|
||||||
|
return None
|
||||||
|
|
||||||
try:
|
try:
|
||||||
user = User.objects.get(id=user_id)
|
user = User.objects.get(id=user_id)
|
||||||
# Verify user belongs to the same tenant
|
# Verify user belongs to the same tenant as the request
|
||||||
if request.user.tenant and user.tenant == request.user.tenant:
|
if user.tenant == tenant:
|
||||||
return user
|
return user
|
||||||
return None
|
return None
|
||||||
except User.DoesNotExist:
|
except User.DoesNotExist:
|
||||||
|
|||||||
Reference in New Issue
Block a user