Delete the token and logout

This commit is contained in:
Amir 2023-02-13 20:33:03 +03:30 committed by GitHub
parent 4abfa28e08
commit 1ba8d25cb2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,4 +1,8 @@
from rest_framework import parsers, renderers from django.shortcuts import get_object_or_404
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required
from django.contrib.auth import logout
from rest_framework import parsers, renderers, status
from rest_framework.authtoken.models import Token from rest_framework.authtoken.models import Token
from rest_framework.authtoken.serializers import AuthTokenSerializer from rest_framework.authtoken.serializers import AuthTokenSerializer
from rest_framework.compat import coreapi, coreschema from rest_framework.compat import coreapi, coreschema
@ -57,6 +61,14 @@ class ObtainAuthToken(APIView):
user = serializer.validated_data['user'] user = serializer.validated_data['user']
token, created = Token.objects.get_or_create(user=user) token, created = Token.objects.get_or_create(user=user)
return Response({'token': token.key}) return Response({'token': token.key})
@method_decorator(login_required)
def delete(self, request, *args, **kwargs):
"""Delete the token and logout."""
token = get_object_or_404(Token, user=request.user)
token.delete()
logout(request)
return Response({'detail': "You've been logged out!"}, status=status.HTTP_205_RESET_CONTENT)
obtain_auth_token = ObtainAuthToken.as_view() obtain_auth_token = ObtainAuthToken.as_view()