Skip to content

Instantly share code, notes, and snippets.

@olamigokayphils
Created January 31, 2023 09:17
Show Gist options
  • Save olamigokayphils/5d37e238048a1ff4d9c2f31f911c8d32 to your computer and use it in GitHub Desktop.
Save olamigokayphils/5d37e238048a1ff4d9c2f31f911c8d32 to your computer and use it in GitHub Desktop.
Auto Logout all active Django sessions
import datetime
from django.conf import settings
from django.contrib.auth import logout
from django.contrib.sessions.models import Session
from django.http import HttpRequest
from importlib import import_module
now = datetime.datetime.now()
session_engine = import_module(settings.SESSION_ENGINE)
sessions = Session.objects.filter(expire_date__gt=now)
for session in sessions:
user = session.get_decoded().get('_auth_user_id')
request = HttpRequest()
request.session = session_engine.SessionStore(session.session_key)
logout(request)
print(f"{user} logged out")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment