mirror of
https://github.com/retspen/webvirtcloud
synced 2026-11-11 12:46:49 +00:00
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.
This commit is contained in:
parent
d9088b410e
commit
6b51c30dd6
8 changed files with 85 additions and 2 deletions
24
accounts/auth.py
Normal file
24
accounts/auth.py
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
"""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"
|
||||
Loading…
Add table
Add a link
Reference in a new issue