Skip to content

Force a Core Portal user to logout

Chandra Y edited this page Jun 11, 2024 · 1 revision

For delete a session of a single user - update replace_me with username

from django.contrib.sessions.models import Session
from django.contrib.auth.models import User
from django.utils import timezone

sessions = Session.objects.filter(expire_date__gte=timezone.now())
for session in sessions:
    data = session.get_decoded()
    user_id = data.get('_auth_user_id')
    if user_id:
        try:
            user = User.objects.get(pk=user_id)
            print(f"Expiry Date: {session.expire_date}, Username: {user.username}")
            if user.username == 'replace_me':
                print('  Deleting session object')
                session.delete()
        except User.DoesNotExist:
            print(f"Username: Unknown (user_id: {user_id})")
    else:
        print(f"Expiry Date: {session.expire_date}, can't find user")
Clone this wiki locally