|
| 1 | +import json |
| 2 | + |
| 3 | +from django.contrib.auth import authenticate, login, logout |
| 4 | + |
| 5 | +from rest_framework import permissions, viewsets, status, views |
| 6 | +from rest_framework.response import Response |
| 7 | + |
| 8 | +from authentication.models import Account |
| 9 | +from authentication.permissions import IsAccountOwner |
| 10 | +from authentication.serializers import AccountSerializer |
| 11 | + |
| 12 | + |
| 13 | +class AccountViewSet(viewsets.ModelViewSet): |
| 14 | + lookup_field = 'username' |
| 15 | + queryset = Account.objects.all() |
| 16 | + serializer_class = AccountSerializer |
| 17 | + |
| 18 | + def get_permissions(self): |
| 19 | + if self.request.method in permissions.SAFE_METHODS: |
| 20 | + return (permissions.AllowAny(),) |
| 21 | + |
| 22 | + if self.request.method == 'POST': |
| 23 | + return (permissions.AllowAny(),) |
| 24 | + |
| 25 | + return (permissions.IsAuthenticated(), IsAccountOwner(),) |
| 26 | + |
| 27 | + def create(self, request): |
| 28 | + serializer = self.serializer_class(data=request.data) |
| 29 | + |
| 30 | + if serializer.is_valid(): |
| 31 | + Account.objects.create_user(**serializer.validated_data) |
| 32 | + |
| 33 | + return Response(serializer.validated_data, status=status.HTTP_201_CREATED) |
| 34 | + |
| 35 | + return Response({ |
| 36 | + 'status': 'Bad request', |
| 37 | + 'message': 'Account could not be created with received data.' |
| 38 | + }, status=status.HTTP_400_BAD_REQUEST) |
| 39 | + |
| 40 | + |
| 41 | +class LoginView(views.APIView): |
| 42 | + def post(self, request, format=None): |
| 43 | + data = json.loads(request.body) |
| 44 | + |
| 45 | + email = data.get('email', None) |
| 46 | + password = data.get('password', None) |
| 47 | + |
| 48 | + account = authenticate(email=email, password=password) |
| 49 | + |
| 50 | + if account is not None: |
| 51 | + if account.is_active: |
| 52 | + login(request, account) |
| 53 | + |
| 54 | + serialized = AccountSerializer(account) |
| 55 | + |
| 56 | + return Response(serialized.data) |
| 57 | + else: |
| 58 | + return Response({ |
| 59 | + 'status': 'Unauthorized', |
| 60 | + 'message': 'This account has been disabled.' |
| 61 | + }, status=status.HTTP_401_UNAUTHORIZED) |
| 62 | + else: |
| 63 | + return Response({ |
| 64 | + 'status': 'Unauthorized', |
| 65 | + 'message': 'Username/password combination invalid.' |
| 66 | + }, status=status.HTTP_401_UNAUTHORIZED) |
| 67 | + |
| 68 | + |
| 69 | +class LogoutView(views.APIView): |
| 70 | + permission_classes = (permissions.IsAuthenticated,) |
| 71 | + |
| 72 | + def post(self, request, format=None): |
| 73 | + logout(request) |
| 74 | + |
| 75 | + return Response({}, status=status.HTTP_204_NO_CONTENT) |
0 commit comments