From a262e59b0203649ffd2f6d351c2cd6979ef1480c Mon Sep 17 00:00:00 2001 From: Daniel Stanton Date: Wed, 25 Jan 2017 13:00:42 +0000 Subject: [PATCH] LogoutAllView deletes all Knox tokens --- rest_auth/urls.py | 9 +++++++-- rest_auth/views.py | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/rest_auth/urls.py b/rest_auth/urls.py index 7a35e9b..6578ba7 100644 --- a/rest_auth/urls.py +++ b/rest_auth/urls.py @@ -1,8 +1,8 @@ from django.conf.urls import url from rest_auth.views import ( - LoginView, LogoutView, UserDetailsView, PasswordChangeView, - PasswordResetView, PasswordResetConfirmView + LoginView, LogoutView, LogoutAllView, UserDetailsView, + PasswordChangeView, PasswordResetView, PasswordResetConfirmView ) urlpatterns = [ @@ -18,3 +18,8 @@ urlpatterns = [ url(r'^password/change/$', PasswordChangeView.as_view(), name='rest_password_change'), ] + +if getattr(settings, 'REST_USE_KNOX', False): + urlpatterns.append( + url(r'^logoutall/$' LogoutAllView.as_view(), name='rest_logout_all'), + ) diff --git a/rest_auth/views.py b/rest_auth/views.py index 4a676f1..147f987 100644 --- a/rest_auth/views.py +++ b/rest_auth/views.py @@ -149,6 +149,39 @@ class LogoutView(APIView): status=status.HTTP_200_OK) +class LogoutAllView(APIView): + """ + Calls Django logout method and deletes all the Knox tokens + assigned to the current User object. + + Accepts/Returns nothing. + """ + authentication_classes = (KnoxTokenAuthentication,) + permission_classes = (IsAuthenticated,) + + def get(self, request, *args, **kwargs): + if getattr(settings, 'ACCOUNT_LOGOUT_ON_GET', False): + response = self.logout(request) + else: + response = self.http_method_not_allowed(request, *args, **kwargs) + + return self.finalize_response(request, response, *args, **kwargs) + + def post(self, request): + return self.logout(request) + + def logout(self, request): + try: + request.user.auth_token_set.all().delete() + except (AttributeError, ObjectDoesNotExist): + pass + + django_logout(request) + + return Response({"detail": _("Successfully logged out.")}, + status=status.HTTP_200_OK) + + class UserDetailsView(RetrieveUpdateAPIView): """ Reads and updates UserModel fields