2
0
mirror of https://github.com/inventree/InvenTree.git synced 2025-05-06 07:18:48 +00:00
InvenTree/InvenTree/users/authentication.py
Oliver f0f4a20f4e
More token tweaks (#5764)
* Update ApiToken model

- Add metadata
- Remove unique_together requirement
- Add last_seen field

* Update admin page for token

* Store metadata against token on creation

* Track last-seen date

* Allow match against existing valid token

- If token is expired or revoked, create a new one
- Prevents duplication of tokens

* Update unit tests
2023-10-21 15:10:11 +11:00

40 lines
1.1 KiB
Python

"""Custom token authentication class for InvenTree API"""
import datetime
from django.utils.translation import gettext_lazy as _
from rest_framework import exceptions
from rest_framework.authentication import TokenAuthentication
from users.models import ApiToken
class ApiTokenAuthentication(TokenAuthentication):
"""Custom implementation of TokenAuthentication class, with custom features:
- Tokens can be revoked
- Tokens can expire
"""
model = ApiToken
def authenticate_credentials(self, key):
"""Adds additional checks to the default token authentication method."""
# If this runs without error, then the token is valid (so far)
(user, token) = super().authenticate_credentials(key)
if token.revoked:
raise exceptions.AuthenticationFailed(_("Token has been revoked"))
if token.expired:
raise exceptions.AuthenticationFailed(_("Token has expired"))
if token.last_seen != datetime.date.today():
# Update the last-seen date
token.last_seen = datetime.date.today()
token.save()
return (user, token)