Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/add flush expired tokens command to admin #721

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions rest_framework_simplejwt/token_blacklist/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

from django.contrib import admin
from django.contrib.auth.models import AbstractBaseUser
from django.core.management import call_command
from django.db.models import QuerySet
from django.utils.translation import gettext_lazy as _
from rest_framework.request import Request
Expand Down Expand Up @@ -67,6 +68,31 @@ class BlacklistedTokenAdmin(admin.ModelAdmin):
"token__jti",
)
ordering = ("token__user",)
actions = ["flush_expired_tokens"]

def flush_expired_tokens(self, request, queryset):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
def flush_expired_tokens(self, request, queryset):
@admin.action(permissions=["change"], description = _("Flush expired tokens"))
def flush_expired_tokens(self, request, queryset):

What are your thoughts on using the @admin.action decorator?
It allows you to set the required permissions for executing an action and provides a description for it as well. Additionally, you can use gettext_lazy to provide localization support. @tpotjj

call_command("flushexpiredtokens")
self.message_user(request, "Flushed expired tokens.")

# Override the changelist_view method to bypass the "no items selected" validation
def changelist_view(self, request, extra_context=None):
"""
Override the default behavior to allow running the custom command
without explicitly selecting any items.
"""
if (
"action" in request.POST
and request.POST["action"] == "flush_expired_tokens"
):
# Modify the queryset to include all items
queryset = self.get_queryset(request)
self.flush_expired_tokens(request, queryset)
# Redirect to the changelist after running the command
return self.response_post_save_change(request, None)

return super().changelist_view(request, extra_context=extra_context)

flush_expired_tokens.short_description = "Flush expired access tokens"

def get_queryset(self, *args, **kwargs) -> QuerySet:
qs = super().get_queryset(*args, **kwargs)
Expand Down
Loading