2014-05-16 16:18:34 +00:00
|
|
|
"""
|
|
|
|
This custom Session model adds an extra column to store an account ID. In
|
|
|
|
real-world applications, it gives you the option of querying the database for
|
|
|
|
all active sessions for a particular account.
|
|
|
|
"""
|
2024-01-26 11:45:07 +00:00
|
|
|
|
2014-05-16 16:18:34 +00:00
|
|
|
from django.contrib.sessions.backends.db import SessionStore as DBStore
|
|
|
|
from django.contrib.sessions.base_session import AbstractBaseSession
|
|
|
|
from django.db import models
|
|
|
|
|
|
|
|
|
|
|
|
class CustomSession(AbstractBaseSession):
|
|
|
|
"""
|
|
|
|
A session model with a column for an account ID.
|
|
|
|
"""
|
2022-02-03 19:24:19 +00:00
|
|
|
|
2014-05-16 16:18:34 +00:00
|
|
|
account_id = models.IntegerField(null=True, db_index=True)
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def get_session_store_class(cls):
|
|
|
|
return SessionStore
|
|
|
|
|
|
|
|
|
|
|
|
class SessionStore(DBStore):
|
|
|
|
"""
|
|
|
|
A database session store, that handles updating the account ID column
|
|
|
|
inside the custom session model.
|
|
|
|
"""
|
2022-02-03 19:24:19 +00:00
|
|
|
|
2014-05-16 16:18:34 +00:00
|
|
|
@classmethod
|
|
|
|
def get_model_class(cls):
|
|
|
|
return CustomSession
|
|
|
|
|
|
|
|
def create_model_instance(self, data):
|
2017-01-21 13:13:44 +00:00
|
|
|
obj = super().create_model_instance(data)
|
2014-05-16 16:18:34 +00:00
|
|
|
|
|
|
|
try:
|
|
|
|
account_id = int(data.get("_auth_user_id"))
|
|
|
|
except (ValueError, TypeError):
|
|
|
|
account_id = None
|
|
|
|
obj.account_id = account_id
|
|
|
|
|
|
|
|
return obj
|
2019-05-19 20:15:45 +00:00
|
|
|
|
|
|
|
def get_session_cookie_age(self):
|
|
|
|
return 60 * 60 * 24 # One day.
|