|
| 1 | +from rest_framework_simplejwt.tokens import RefreshToken |
| 2 | +from rest_framework.response import Response |
| 3 | +from django.contrib.auth import authenticate |
| 4 | +from rest_framework import status, generics |
| 5 | +from django.conf import settings |
| 6 | + |
| 7 | +from authentication.serializers import AuthUserSerializer |
| 8 | + |
| 9 | + |
| 10 | +def get_tokens_for_user(user): |
| 11 | + refresh = RefreshToken.for_user(user) |
| 12 | + |
| 13 | + return { |
| 14 | + "refresh": str(refresh), |
| 15 | + "access": str(refresh.access_token), |
| 16 | + } |
| 17 | + |
| 18 | + |
| 19 | +class LoginView(generics.GenericAPIView): |
| 20 | + permission_classes = [] |
| 21 | + authentication_classes = [] |
| 22 | + serializer_class = AuthUserSerializer |
| 23 | + |
| 24 | + def post(self, request, format=None): |
| 25 | + data = request.data |
| 26 | + response = Response() |
| 27 | + username = data.get("username", None) |
| 28 | + password = data.get("password", None) |
| 29 | + user = authenticate(username=username, password=password) |
| 30 | + |
| 31 | + if user is not None: |
| 32 | + if user.is_active: |
| 33 | + data = get_tokens_for_user(user) |
| 34 | + response.set_cookie( |
| 35 | + key=settings.SIMPLE_JWT["AUTH_COOKIE"], |
| 36 | + value=data["access"], |
| 37 | + secure=settings.SIMPLE_JWT["AUTH_COOKIE_SECURE"], |
| 38 | + httponly=settings.SIMPLE_JWT["AUTH_COOKIE_HTTP_ONLY"], |
| 39 | + samesite=settings.SIMPLE_JWT["AUTH_COOKIE_SAMESITE"], |
| 40 | + max_age=823396, |
| 41 | + ) |
| 42 | + response.data = data |
| 43 | + response.status_code = status.HTTP_200_OK |
| 44 | + return response |
| 45 | + else: |
| 46 | + return Response( |
| 47 | + {"details": "This account is not active."}, |
| 48 | + status=status.HTTP_400_BAD_REQUEST, |
| 49 | + ) |
| 50 | + else: |
| 51 | + return Response( |
| 52 | + {"details": "Account with given credentials not found."}, |
| 53 | + status=status.HTTP_400_BAD_REQUEST, |
| 54 | + ) |
| 55 | + |
| 56 | + |
| 57 | +class LogoutView(generics.GenericAPIView): |
| 58 | + permission_classes = [] |
| 59 | + authentication_classes = [] |
| 60 | + serializer_class = None |
| 61 | + |
| 62 | + def post(self, request): |
| 63 | + response = Response() |
| 64 | + response.set_cookie( |
| 65 | + key=settings.SIMPLE_JWT["AUTH_COOKIE"], |
| 66 | + max_age=0, |
| 67 | + secure=settings.SIMPLE_JWT["AUTH_COOKIE_SECURE"], |
| 68 | + expires="Thu, 01 Jan 1970 00:00:00 GMT", |
| 69 | + samesite=settings.SIMPLE_JWT["AUTH_COOKIE_SAMESITE"], |
| 70 | + ) |
| 71 | + response.data = {"detail": "Logout successful."} |
| 72 | + return response |
0 commit comments