From 1ba8d25cb25fc80dd221ce7673a0bcc09d9f68af Mon Sep 17 00:00:00 2001 From: Amir <84547283+amir4v@users.noreply.github.com> Date: Mon, 13 Feb 2023 20:33:03 +0330 Subject: [PATCH] Delete the token and logout --- rest_framework/authtoken/views.py | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/rest_framework/authtoken/views.py b/rest_framework/authtoken/views.py index 50f9acbd9..ec18299da 100644 --- a/rest_framework/authtoken/views.py +++ b/rest_framework/authtoken/views.py @@ -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.serializers import AuthTokenSerializer from rest_framework.compat import coreapi, coreschema @@ -57,6 +61,14 @@ class ObtainAuthToken(APIView): user = serializer.validated_data['user'] token, created = Token.objects.get_or_create(user=user) 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()