Created
May 31, 2018 15:57
-
-
Save llybin/78e0437923a1b155190bb15467f7b31a to your computer and use it in GitHub Desktop.
Django management command logout user
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
from django.core.management import BaseCommand | |
from django.contrib.auth.models import User | |
from django.contrib.sessions.models import Session | |
from django.db.models import Q | |
from rest_framework.authtoken.models import Token | |
class Command(BaseCommand): | |
help = "Logout user" | |
def add_arguments(self, parser): | |
parser.add_argument( | |
'email', | |
type=str, | |
help='User email' | |
) | |
def handle(self, *args, **options): | |
users = User.objects.filter(Q(email=options['email']) | Q(username=options['email'])) | |
for user in users: | |
print("User: {}, {}, {}".format(user.id, user.email, user.username)) | |
print("Sessions deleting...") | |
for s in Session.objects.all(): | |
if s.get_decoded().get('_auth_user_id') == str(user.id): | |
s.delete() | |
print("\tSession was deleted") | |
print('Done') | |
print("Tokens deleting...") | |
result = Token.objects.filter(user_id=user.id).delete() | |
if result[0]: | |
print("\tTokens was deleted") | |
print('Done') | |
print('Successfully logout {} user.'.format(options['email'])) |
How do you use this file? Thank you!
It is Django management command. Follow instructions from django docs
https://docs.djangoproject.com/en/2.2/howto/custom-management-commands/
After that you will be able to use that functionality by wrtiting following code
python manage.py user_logout
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How do you use this file? Thank you!