API Tokens #134

Merged
Dalai Felinto merged 6 commits from tokens into main 2024-05-27 12:53:31 +02:00
2 changed files with 26 additions and 0 deletions
Showing only changes of commit cdf12cdf60 - Show all commits

View File

@ -277,6 +277,7 @@ REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication',
dfelinto marked this conversation as resolved Outdated

why do we need SessionAuthentication and BasicAuthentication?

if we plan to use only our own UserTokenAuthentication, checking the header on each request, we won't need the other mechanisms

why do we need SessionAuthentication and BasicAuthentication? if we plan to use only our own UserTokenAuthentication, checking the header on each request, we won't need the other mechanisms
'tokens.authentication.UserTokenAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',),
}

25
tokens/authentication.py Normal file
View File

@ -0,0 +1,25 @@
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from .models import UserToken
class UserTokenAuthentication(BaseAuthentication):
def authenticate(self, request):
auth_header = request.headers.get('Authorization')
if not auth_header:
return None
try:
token_type, token_key = auth_header.split()
if token_type.lower() != 'bearer':
return None
except ValueError:
return None
try:
token = UserToken.objects.get(token=token_key)
except UserToken.DoesNotExist:
raise AuthenticationFailed('Invalid token')
return (token.user, token)