From edc4468770a77c35d76f3c1fc92c0fbfd44d13f3 Mon Sep 17 00:00:00 2001 From: Vignesh Hari Date: Tue, 1 Mar 2022 02:10:26 +0530 Subject: [PATCH] Add Token based auth --- care/users/api/viewsets/users.py | 15 +++++++++++++++ config/settings/base.py | 2 ++ 2 files changed, 17 insertions(+) diff --git a/care/users/api/viewsets/users.py b/care/users/api/viewsets/users.py index 6a1cb515ac..226a826918 100644 --- a/care/users/api/viewsets/users.py +++ b/care/users/api/viewsets/users.py @@ -6,6 +6,7 @@ from rest_framework import filters as drf_filters from rest_framework import filters as rest_framework_filters from rest_framework import mixins, status +from rest_framework.authtoken.models import Token from rest_framework.decorators import action from rest_framework.generics import get_object_or_404 from rest_framework.permissions import IsAuthenticated @@ -115,6 +116,20 @@ def getcurrentuser(self, request): status=status.HTTP_200_OK, data=UserSerializer(request.user, context={"request": request}).data, ) + @action(detail=False, methods=["GET"]) + def get_token(self, request): + if not request.user.is_authenticated: + raise PermissionError + token, _ = Token.objects.get_or_create(user=request.user) + return Response(status=status.HTTP_200_OK, data={"token": token.key}) + + @action(detail=False, methods=["GET"]) + def delete_token(self, request): + if not request.user.is_authenticated: + raise PermissionError + Token.objects.filter(user=request.user).delete() + return Response(status=status.HTTP_204_NO_CONTENT) + def destroy(self, request, *args, **kwargs): queryset = self.queryset username = kwargs["username"] diff --git a/config/settings/base.py b/config/settings/base.py index f4405499be..cc02ae00ac 100644 --- a/config/settings/base.py +++ b/config/settings/base.py @@ -86,6 +86,7 @@ "allauth.socialaccount", "storages", "rest_framework", + "rest_framework.authtoken", "drf_yasg", "drf_extra_fields", "location_field.apps.DefaultConfig", @@ -308,6 +309,7 @@ "config.authentication.CustomJWTAuthentication", "config.authentication.CustomBasicAuthentication", "rest_framework.authentication.SessionAuthentication", + "rest_framework.authentication.TokenAuthentication", ), "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.LimitOffsetPagination", "PAGE_SIZE": 14,