Skip to content

Instantly share code, notes, and snippets.

@tclancy
Forked from playpauseandstop/gist:1818351
Last active May 9, 2022 12:07
  • Star 7 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
Django management command to expire all sessions
import datetime
from django.conf import settings
from django.contrib.auth import logout
from django.contrib.auth.models import User
from django.contrib.sessions.models import Session
from django.core.management.base import NoArgsCommand
from django.http import HttpRequest
from django.utils.importlib import import_module
def init_session(session_key):
"""
Initialize same session as done for ``SessionMiddleware``.
"""
engine = import_module(settings.SESSION_ENGINE)
return engine.SessionStore(session_key)
class Command(NoArgsCommand):
help = "Kill all active sessions"
def handle_noargs(self, **options):
"""
Read all available users and all available not expired sessions. Then
logout from each session. Start with a day ago to hack around the
timezone issue instead of doing something smart.
"""
start = datetime.datetime.now() - datetime.timedelta(days=1)
request = HttpRequest()
sessions = Session.objects.filter(expire_date__gt=start)
print('Found %d not-expired session(s).' % len(sessions))
for session in sessions:
username = session.get_decoded().get('_auth_user_id')
request.session = init_session(session.session_key)
logout(request)
print('Successfully logout %r user.' % username)
print('All OK!')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment