Skip to content

Instantly share code, notes, and snippets.

@mthri
Created January 11, 2021 06:21
Show Gist options
  • Save mthri/6fef7019e2433a6eedfc8fa3bf55959e to your computer and use it in GitHub Desktop.
Save mthri/6fef7019e2433a6eedfc8fa3bf55959e to your computer and use it in GitHub Desktop.
each user one session in django - also works on redis as cache engine
def login_one_session(request, user):
from importlib import import_module
from django.core.cache import cache
# Get Session Key and Prefix
from django.contrib.auth import SESSION_KEY
from django.contrib.sessions.backends.cache import KEY_PREFIX
# login authorized user
login(request, user)
# remove prefix of all session key
all_keys = [key.split(KEY_PREFIX)[-1] for key in cache.keys(KEY_PREFIX+'*')]
# get session engine
engine = import_module(settings.SESSION_ENGINE)
SessionStore = engine.SessionStore
# get curent user session key
current_session_key = request.session.session_key
# search for duplicate key
for key in all_keys:
# try to extract user id from each session
session = SessionStore(key)
user_id = session.get(SESSION_KEY)
# if finde another session key from curent user, delete that!
if user_id and int(user_id) is request.user.id and current_session_key is not session.session_key:
cache.delete_pattern(KEY_PREFIX + session.session_key)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment