1. """
    
  2. This custom Session model adds an extra column to store an account ID. In
    
  3. real-world applications, it gives you the option of querying the database for
    
  4. all active sessions for a particular account.
    
  5. """
    
  6. from django.contrib.sessions.backends.db import SessionStore as DBStore
    
  7. from django.contrib.sessions.base_session import AbstractBaseSession
    
  8. from django.db import models
    
  9. 
    
  10. 
    
  11. class CustomSession(AbstractBaseSession):
    
  12.     """
    
  13.     A session model with a column for an account ID.
    
  14.     """
    
  15. 
    
  16.     account_id = models.IntegerField(null=True, db_index=True)
    
  17. 
    
  18.     @classmethod
    
  19.     def get_session_store_class(cls):
    
  20.         return SessionStore
    
  21. 
    
  22. 
    
  23. class SessionStore(DBStore):
    
  24.     """
    
  25.     A database session store, that handles updating the account ID column
    
  26.     inside the custom session model.
    
  27.     """
    
  28. 
    
  29.     @classmethod
    
  30.     def get_model_class(cls):
    
  31.         return CustomSession
    
  32. 
    
  33.     def create_model_instance(self, data):
    
  34.         obj = super().create_model_instance(data)
    
  35. 
    
  36.         try:
    
  37.             account_id = int(data.get("_auth_user_id"))
    
  38.         except (ValueError, TypeError):
    
  39.             account_id = None
    
  40.         obj.account_id = account_id
    
  41. 
    
  42.         return obj
    
  43. 
    
  44.     def get_session_cookie_age(self):
    
  45.         return 60 * 60 * 24  # One day.