Last active
November 24, 2022 11:25
-
-
Save eshaan7/4485a089c4f51420067d3bcf0b5fa6ab to your computer and use it in GitHub Desktop.
Custom admin view for simplejwt that allows bulk deletion, blacklisting and token creation. Issue on GitHub: https://github.com/SimpleJWT/django-rest-framework-simplejwt/issues/258
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
from django.contrib import admin | |
from rest_framework_simplejwt.token_blacklist.admin import OutstandingTokenAdmin | |
from rest_framework_simplejwt.token_blacklist.models import OutstandingToken | |
from rest_framework_simplejwt.tokens import SlidingToken, RefreshToken | |
class CustomOutstandingTokenAdmin(OutstandingTokenAdmin): | |
""" | |
Custom admin view for OutstandingToken model\n | |
allows bulk deletion, blacklisting and sliding token creation | |
""" | |
def blacklist_selected_tokens(modeladmin, request, queryset): | |
for obj in queryset: | |
try: | |
SlidingToken(str(obj.token)).blacklist() | |
except Exception: | |
RefreshToken(str(obj.token)).blacklist() | |
except Exception: | |
pass | |
actions = [blacklist_selected_tokens] | |
__fieldsets_custom = [ | |
( | |
"Sliding Token", | |
{ | |
"fields": ("user",), | |
"description": """ | |
<h3>Token will be generated on save.</h3> | |
""", | |
}, | |
), | |
] | |
def add_view(self, request, extra_content=None): | |
self.fieldsets = self.__fieldsets_custom | |
return super(CustomOutstandingTokenAdmin, self).add_view(request) | |
def get_readonly_fields(self, *args, **kwargs): | |
fields = [f.name for f in self.model._meta.fields] | |
# only user field is writeable | |
fields.remove("user") | |
return fields | |
def has_delete_permission(self, *args, **kwargs): | |
return True | |
def has_add_permission(self, *args, **kwargs): | |
return True | |
def has_change_permission(self, *args, **kwargs): | |
return False | |
def save_model(self, request, obj, form, change): | |
if obj.user: | |
SlidingToken.for_user(obj.user) | |
# Unregister the default admin view | |
admin.site.unregister(OutstandingToken) | |
# Register our custom admin view | |
admin.site.register(OutstandingToken, CustomOutstandingTokenAdmin) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment