Reputation: 31
I want to destroy auth token when user get logged out. User get logged out successfully in the view that I have provided.But I need to destroy token when user get logout.
views.py
class UserLoginViewSet(viewsets.ViewSet):
def create(self,request):
try:
data=request.data
email=data.get('email')
password=data.get('password')
date_of_birth=data.get('date_of_birth')
if not all([email,password,date_of_birth]):
raise Exception('all fields are mandetory')
user=authenticate(username=email,password=password)
if user is not None:
token=generate_token()
user_info=MyUser.objects.get(email=email)
data=({
'email':user_info.email,
'password':user_info.password,
#'data_of_birth':user_info.data_of_birth
})
return Response({"message": "You are successfully logged in",
"user_info":data,"token": token, "success": True},status=status.HTTP_200_OK)
else :
raise Exception('not authorised')
except Exception as error:
traceback.print_exc()
return Response({"message": str(error), "success": False}, status=status.HTTP_200_OK)
def delete(self,request):
logout(request)
return Response({'successfull':True})```
#my user is logging out correctly,but i want to doi this by deleting token
Upvotes: 1
Views: 1036
Reputation: 332
you can do like this
class UserLoginViewSet(viewsets.ViewSet):
def create(self,request):
try:
data=request.data
email=data.get('email')
password=data.get('password')
date_of_birth=data.get('date_of_birth')
if not all([email,password,date_of_birth]):
raise Exception('all fields are mandetory')
user=authenticate(username=email,password=password)
if user is not None:
token=generate_token()
user_info=MyUser.objects.get(email=email)
data=({
'email':user_info.email,
'password':user_info.password,
#'data_of_birth':user_info.data_of_birth
})
return Response({"message": "You are successfully logged in",
"user_info":data,"token": token, "success": True},status=status.HTTP_200_OK)
else :
raise Exception('not authorised')
except Exception as error:
traceback.print_exc()
return Response({"message": str(error), "success": False}, status=status.HTTP_200_OK)
class LogoutView(APIView):
permission_classes = (permissions.IsAuthenticated,)
def get(self, request):
request.user.auth_token.delete()
logout(request)
return Response({"message": "success", 'code': status.HTTP_200_OK, 'detail': "logout success"})
In app urls.py add new url:
path('logout/',LogoutView.as_view()),
Upvotes: 1