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

1"""Custom token authentication class for InvenTree API.""" 

2 

3import datetime 

4 

5from django.utils.translation import gettext_lazy as _ 

6 

7from oauth2_provider.contrib.rest_framework import OAuth2Authentication 

8from rest_framework import exceptions 

9from rest_framework.authentication import TokenAuthentication 

10 

11import users.models 

12 

13 

14class ApiTokenAuthentication(TokenAuthentication): 

15 """Custom implementation of TokenAuthentication class, with custom features. 

16 

17 Changes: 

18 - Tokens can be revoked 

19 - Tokens can expire 

20 """ 

21 

22 model = users.models.ApiToken 

23 

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) 

28 

29 if token.revoked: 

30 raise exceptions.AuthenticationFailed(_('Token has been revoked')) 

31 

32 if token.expired: 

33 raise exceptions.AuthenticationFailed(_('Token has expired')) 

34 

35 if token.last_seen != datetime.date.today(): 

36 # Update the last-seen date 

37 token.last_seen = datetime.date.today() 

38 token.save() 

39 

40 return (user, token) 

41 

42 

43class ExtendedOAuth2Authentication(OAuth2Authentication): 

44 """Custom implementation of OAuth2Authentication class to support custom scope rendering."""