djangopostgresqldjango-tenants

How to handle authentication and AUTH_USER_MODEL in Django multi-tenant with separate schemas in PostgreSQL?


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.


📌 System Requirements

  1. Global superadmins that manage the system and are stored in the public database (public).
  2. Tenant users, who exist in their respective tenant database and have relationships with other tables inside their own database.
  3. Separate authentication: Superadmins should authenticate in the public database. Tenant users should authenticate within their specific tenant database.

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.


❌ Current Issue

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.


✅ Possible Solution

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?.


Solution

  • 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:

    1. Centralized User Model: Use a single user model in the public schema to centralize authentication. PostgreSQL supports relationships across schemas.

    2. 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.

    3. Token Validation: JWT tokens are managed centrally and contain information about the tenant, ensuring data is secure and accessible only to the appropriate tenant.