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

Add token filter and action #1058

Merged
merged 5 commits into from
Nov 13, 2024
Merged
Changes from 2 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
58 changes: 57 additions & 1 deletion docker-app/qfieldcloud/authentication/admin.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,49 @@
from django.contrib import admin
from django.contrib.admin import register
from django.db.models import Q, QuerySet
from django.utils import timezone

from .models import AuthToken


class AuthTokenClientTypeFilter(admin.SimpleListFilter):
# Human-readable title which will be displayed
title = "Client type"

# Parameter for the filter that will be used in the URL query.
parameter_name = "client_type"

def lookups(self, request, model_admin):
"""
Returns a list of tuples. The first element in each
tuple is the coded value for the option that will
appear in the URL query. The second element is the
human-readable name for the option that will appear
in the right sidebar.
Here it is just the several available AuthToken.ClientType
gounux marked this conversation as resolved.
Show resolved Hide resolved
"""
return AuthToken.ClientType.choices

def queryset(self, request, queryset) -> QuerySet:
"""
Returns the filtered queryset based on the value
provided in the query string and retrievable via
`self.value()`.
"""
value = self.value()

if value is None:
return queryset

accepted_values = [ct[0] for ct in AuthToken.ClientType.choices]
if value not in accepted_values:
raise NotImplementedError(
f"Unknown client type: {value} (was expecting: {','.join(accepted_values)})"
)

return queryset.filter(Q(client_type=value))


@register(AuthToken)
class AuthTokenAdmin(admin.ModelAdmin):
list_display = ("user", "created_at", "expires_at", "last_used_at", "client_type")
Expand All @@ -15,6 +55,22 @@ class AuthTokenAdmin(admin.ModelAdmin):
"client_type",
"user_agent",
)
list_filter = ("created_at", "last_used_at", "expires_at")
list_filter = (
"created_at",
"last_used_at",
"expires_at",
AuthTokenClientTypeFilter,
)

actions = ("expire_selected_tokens",)

search_fields = ("user__username__iexact", "client_type", "key__startswith")

def expire_selected_tokens(self, request, queryset):
"""
Sets a set of tokens to expired
by updating the expires_at date to now
Expires only valid tokens
gounux marked this conversation as resolved.
Show resolved Hide resolved
"""
now = timezone.now()
queryset.filter(Q(expires_at__gt=now)).update(expires_at=now)
Loading