27 lines
972 B
Python
27 lines
972 B
Python
"""Custom JWT authentication that touches `User.last_active_at` on each request."""
|
|
|
|
from datetime import timedelta
|
|
|
|
from django.utils import timezone
|
|
from rest_framework_simplejwt.authentication import JWTAuthentication
|
|
|
|
|
|
class TrackingJWTAuthentication(JWTAuthentication):
|
|
"""Wraps simplejwt's auth and bumps `last_active_at` whenever an authenticated
|
|
request comes in. Debounced — at most one DB write per user per `DEBOUNCE_SECONDS`.
|
|
"""
|
|
|
|
DEBOUNCE_SECONDS = 5 * 60 # 5 minutes
|
|
|
|
def authenticate(self, request):
|
|
result = super().authenticate(request)
|
|
if result is None:
|
|
return None
|
|
user, validated_token = result
|
|
now = timezone.now()
|
|
last = user.last_active_at
|
|
if last is None or (now - last).total_seconds() > self.DEBOUNCE_SECONDS:
|
|
type(user).objects.filter(pk=user.pk).update(last_active_at=now)
|
|
user.last_active_at = now
|
|
return user, validated_token
|