1
0
Fork 0
mirror of https://github.com/retspen/webvirtcloud synced 2026-11-08 19:26:48 +00:00
webvirtcloud/accounts/auth.py
catborise 6b51c30dd6 feat(accounts): API tokens show their last use, and a user has at most ten
The API Tokens tab gets a "Last used" column, so an unused token can be
told from one a script still needs. The token's last use is written when
it authenticates, at most once a minute (accounts.auth.TokenAuthentication,
knox's class with that one addition; the API schema describes it as
knox's).

A user has at most ten tokens; a new one is refused until one is
deleted. Expired tokens do not count, and are deleted when a new token is
made.
2026-10-25 10:16:52 +03:00

24 lines
922 B
Python

"""API token authentication: knox's, noting when each token was last used."""
from datetime import timedelta
from django.utils import timezone
from drf_spectacular.contrib.knox_auth_token import KnoxTokenScheme
from knox.auth import TokenAuthentication as KnoxTokenAuthentication
# a token's last use is written at most once a minute, not on every request
LAST_USED_EVERY = timedelta(minutes=1)
class TokenAuthentication(KnoxTokenAuthentication):
def validate_user(self, auth_token):
user, token = super().validate_user(auth_token)
now = timezone.now()
if token.last_used is None or now - token.last_used >= LAST_USED_EVERY:
type(token).objects.filter(pk=token.pk).update(last_used=now)
return user, token
class TokenScheme(KnoxTokenScheme):
"""The API schema's description of these tokens, as of knox's."""
target_class = "accounts.auth.TokenAuthentication"