Extending cache session with additional data in middleware


I’m currently managing a multitenant Django app that uses django-pgschemas. The client-facing service is a headless API backend, so we’re using a custom header to identify the client and redirect the request to the corresponding tenant. No worries there.

Internally we have client-specific Django admins that use custom cookies to store the tenant ID. However, we’re logged out within minutes of inactivity (whereas the session is still valid). Thus I’d like to store the tenant ID in the session store (and set the tenant with custom middleware) to bypass the problem.

However, I’m not able to find any notes/blogs about extending the Cache session (using redis). Am I missing something elementary ? If not could someone point me in the right direction ?

The session isn’t the best place to store data like that - there’s no guarantee that a session will persist across login/logout.

If a user is going to be associated with one specific tenant ID at any one point in time, and that assignment should persist across logins, you’d be better off storing that ID in the User object itself if you’re using a custom user, or in a user-profile object if you aren’t.

Got it working. I was trying to prevent session collisions for multiple admins completely forgetting that django supports multiple admins officially. So they already have ways to avoid this noise and I just had to move my new schema middleware after the session middleware

Thanks @KenWhitesell but my setup has mutiple sets of user models.

Each tenant is associated with different postgres schema. Within each one, there are independent user tables. So associating a user with a field would not have worked for me