Corvia / django-tenant-users

Adds global user authentication and tenant-specific permissions to django-tenants.
https://django-tenant-users.rtfd.io
MIT License
341 stars 65 forks source link

Django rest framework with django-tenant and django-tenant-users (TenantUser object has no atttribute tenant) #606

Closed firmansyahrr closed 1 month ago

firmansyahrr commented 4 months ago

Hello,

I try to create backend application using django rest framework, django tenants and django tenant users. I have a problem. I got this error 'TenantUser' object has no attribute 'tenant' when try to custom my class to add tenant information when the jwt obtain new token.

Here is my custom class

class CustomTokenObtainPairSerializer(TokenObtainPairSerializer):
    @classmethod
    def get_token(cls, user) -> Token:
        token = super().get_token(user)
        token['tenant_id'] = user.tenant.id
        return token

And here is my settings.py

SHARED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    "tenant_users.permissions",
    "tenant_users.tenants",
    'rest_framework',
    'django_tenants',
    'app',
    'users',
]

TENANT_APPS = [
    'tenant_app',
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "tenant_users.permissions",
    'rest_framework',
    'rest_framework_simplejwt',
]

INSTALLED_APPS = SHARED_APPS + [app for app in TENANT_APPS if app not in SHARED_APPS]

any suggestion about this error.

Thanks.

Wizely99 commented 4 months ago

I have limited experience with JWT tokens, but to obtain a tenant instance, you would:

  1. Use the request to get the current tenant via request.tenant.
  2. Retrieve all tenants associated with the user by utilizing user.tenants.all().

Note that tenants is a many-to-many field on the user model, allowing you to apply queryset methods to it. Hope that helps