From 580a5ca8d08d4b4cb31d3b5b9a1b03daf3858432 Mon Sep 17 00:00:00 2001 From: Sverre Nystad Date: Thu, 4 Jan 2024 20:29:52 +0100 Subject: [PATCH] Feat: Add login view with authentication --- backend/users/views.py | 32 +++++++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/backend/users/views.py b/backend/users/views.py index f4b22f23..192907b3 100644 --- a/backend/users/views.py +++ b/backend/users/views.py @@ -1,10 +1,40 @@ from django.shortcuts import render +from django.contrib.auth import authenticate # Create your views here. from rest_framework import generics -from .serializers import UserSerializer +from rest_framework.decorators import api_view +from rest_framework.response import Response +from rest_framework import status + +from drf_yasg.utils import swagger_auto_schema + +# from drf_yasg import openapi + +from .serializers import UserSerializer, LoginSerializer class CreateUserView(generics.CreateAPIView): serializer_class = UserSerializer + + +@swagger_auto_schema( + method="post", + request_body=LoginSerializer, + operation_description="Login to the application", +) +@api_view(["POST"]) +def LoginView(request): + username = request.data.get("username") + password = request.data.get("password") + user = authenticate(username=username, password=password) + + if user is not None: + # Login successful + return Response({"message": "Login successful"}, status=status.HTTP_200_OK) + else: + # Login failed + return Response( + {"message": "Invalid credentials"}, status=status.HTTP_401_UNAUTHORIZED + )