I’m developing a multi-tenant SaaS application using Django, where each tenant has its own separate database with its own schema and relationships. However, I'm struggling with how to properly manage authentication and define AUTH_USER_MODEL in this environment.
The main problem is that Django allows only one AUTH_USER_MODEL, but I need to manage users separately for each tenant while maintaining the ability to associate them with other tables within their respective databases.
If I define a single user model in AUTH_USER_MODEL, I cannot differentiate between global superadmins and tenant users, nor can I correctly manage relationships within each database.
I tried defining two different user models, but Django does not allow multiple AUTH_USER_MODEL, which complicates authentication.
I thought of defining a base model BaseUser that extends AbstractUser, and then creating two inherited models.
But I am not sure which is the right way, there is another?.
I've been researching how to handle authentication in multi-tenant systems with Django and PostgreSQL, and I consulted ChatGPT. It suggested that a standard practice is:
Centralized User Model: Use a single user model in the public
schema to centralize authentication. PostgreSQL supports relationships across schemas.
Tenant Relationship: Each user in public
is linked to a specific tenant through an identifier or foreign key, making user management easier and ensuring data isolation.
Token Validation: JWT tokens are managed centrally and contain information about the tenant, ensuring data is secure and accessible only to the appropriate tenant.