Coverage for src/backend/InvenTree/users/authentication.py: 40%
19 statements
« prev ^ index » next coverage.py v7.15.2, created at 2026-10-07 17:47 +0000
« prev ^ index » next coverage.py v7.15.2, created at 2026-10-07 17:47 +0000
1"""Custom token authentication class for InvenTree API."""
3import datetime
5from django.utils.translation import gettext_lazy as _
7from oauth2_provider.contrib.rest_framework import OAuth2Authentication
8from rest_framework import exceptions
9from rest_framework.authentication import TokenAuthentication
11import users.models
14class ApiTokenAuthentication(TokenAuthentication):
15 """Custom implementation of TokenAuthentication class, with custom features.
17 Changes:
18 - Tokens can be revoked
19 - Tokens can expire
20 """
22 model = users.models.ApiToken
24 def authenticate_credentials(self, key):
25 """Adds additional checks to the default token authentication method."""
26 # If this runs without error, then the token is valid (so far)
27 (user, token) = super().authenticate_credentials(key)
29 if token.revoked:
30 raise exceptions.AuthenticationFailed(_('Token has been revoked'))
32 if token.expired:
33 raise exceptions.AuthenticationFailed(_('Token has expired'))
35 if token.last_seen != datetime.date.today():
36 # Update the last-seen date
37 token.last_seen = datetime.date.today()
38 token.save()
40 return (user, token)
43class ExtendedOAuth2Authentication(OAuth2Authentication):
44 """Custom implementation of OAuth2Authentication class to support custom scope rendering."""