diff --git a/user/urls.py b/user/urls.py index 5c74280..b5d7311 100644 --- a/user/urls.py +++ b/user/urls.py @@ -1,9 +1,7 @@ from django.conf import settings -from django.urls import path from rest_framework import routers -from .views import login_view, logout_view from .viewsets import UserViewset @@ -14,7 +12,4 @@ else: router.register("users", UserViewset) -urlpatterns = router.urls + [ - path("login/", login_view), - path("logout/", logout_view), -] +urlpatterns = router.urls diff --git a/user/views.py b/user/views.py deleted file mode 100644 index 3df2397..0000000 --- a/user/views.py +++ /dev/null @@ -1,26 +0,0 @@ -from django.contrib.auth import authenticate -from django.contrib.auth import login, logout - -from rest_framework.response import Response - -from .serializers import UserSerializer - - -def login_view(request): - if request.method == "POST": - username = request.data["username"] - password = request.data["password"] - user = authenticate(request, username=username, password=password) - if user is not None: - login(request, user) - serializer = UserSerializer(user) - return Response(serializer.data) - else: - return Response(status=401) - else: - return Response(status=405) - - -def logout_view(request): - logout(request) - return Response(status=204) diff --git a/user/viewsets.py b/user/viewsets.py index b250b6b..55a0832 100644 --- a/user/viewsets.py +++ b/user/viewsets.py @@ -1,4 +1,4 @@ -from django.contrib.auth import login +from django.contrib.auth import authenticate, login, logout from rest_framework.decorators import action from rest_framework.permissions import AllowAny, IsAdminUser, IsAuthenticated @@ -50,3 +50,19 @@ class UserViewset(ActionBasedMixin, ModelViewSet): def me(self, request): serializer = self.get_serializer(request.user) return Response(serializer.data) + + @action(detail=False, methods=["POST"]) + def login(self, request): + username = request.data["username"] + password = request.data["password"] + user = authenticate(request, username=username, password=password) + if user is not None: + login(request, user) + serializer = UserSerializer(user) + return Response(serializer.data) + return Response(status=401) + + @action(detail=False, methods=["POST"]) + def logout(self, request): + logout(request) + return Response(status=204)