diff --git a/netbox/netbox/api/authentication.py b/netbox/netbox/api/authentication.py index ea66dc5a6..1b7def3a3 100644 --- a/netbox/netbox/api/authentication.py +++ b/netbox/netbox/api/authentication.py @@ -1,7 +1,11 @@ +import logging + from django.conf import settings +from django.utils import timezone from rest_framework import authentication, exceptions from rest_framework.permissions import BasePermission, DjangoObjectPermissions, SAFE_METHODS +from netbox.config import get_config from users.models import Token from utilities.request import get_client_ip @@ -40,6 +44,17 @@ class TokenAuthentication(authentication.TokenAuthentication): except model.DoesNotExist: raise exceptions.AuthenticationFailed("Invalid token") + # Update last used, but only once a minute. This reduces the write load on the db + if not token.last_used or (timezone.now() - token.last_used).total_seconds() > 60: + # If maintenance mode is enabled, assume the database is read-only, and disable updating the token's + # last_used time upon authentication. + if get_config().MAINTENANCE_MODE: + logger = logging.getLogger('netbox.auth.login') + logger.warning("Maintenance mode enabled: disabling update of token's last used timestamp") + else: + token.last_used = timezone.now() + token.save() + # Enforce the Token's expiration time, if one has been set. if token.is_expired: raise exceptions.AuthenticationFailed("Token expired") diff --git a/netbox/templates/users/api_tokens.html b/netbox/templates/users/api_tokens.html index 360e65a67..24b32cc9b 100644 --- a/netbox/templates/users/api_tokens.html +++ b/netbox/templates/users/api_tokens.html @@ -34,6 +34,14 @@ Never {% endif %} +