2
0
mirror of https://github.com/inventree/InvenTree.git synced 2025-04-28 11:36:44 +00:00
InvenTree/InvenTree/users/authentication.py
Oliver 23ea746813
Api token updates (#5664)
* Create new APIToken model

- Has custom 'name' field
- Has custom expiry date

* Add data migration to port across any existing user tokens

* Adds 'revoked' field - tokens can be manually revoked

* Update API token - allow multiple tokens per user

* Custom token auth handler

- Correctly handles revoked tokens
- Correctly handles expired tokens

* Update AuthRequiredMiddleware

- Check for token active status

* Token API endpoint improvements

- Can return tokens with custom names
- Return more information on the token too

* Consolidate migrations

* When requesting a token, overwrite inactive token for authenticated user

- An authenticated user must receive a token
- Unauthenticated users cannot do this

* Fix

* Use token name for frontend

* Force token expiry, and generate default expiry date

* Force generation of a new token when requested

* Reduce data exposed on token API endpoint

* Display redacted token in admin site

* Log when new token is created for user

* Add default value for token

- Allows raw token to be viewed in the admin interface when created
- After created, no longer visible
- Also provides ability to generate token with static prefix

* Fixes for admin interface

- Prevent user and expiry from being edited after creation

* Implement unit tests for token functionality

* Fix content exclude for import/export

* Fix typo

* Further tweaks

- Prevent editing of "name" field after creation
- Add isoformat date suffix to token

* Longer token requires longer database field!

* Fix other API tokens

* Remove 'delete' method from token API endpoint

* Bump API version
2023-10-20 14:06:06 +11:00

33 lines
965 B
Python

"""Custom token authentication class for InvenTree API"""
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"))
return (user, token)