Fakultas Ilmu Komputer UI

views.py 2.25 KB
Newer Older
Glenda Emanuella Sutanto's avatar
Glenda Emanuella Sutanto committed
1
2
from rest_framework import viewsets, status
from rest_framework.response import Response
3
4
5
6
from rest_framework.views import APIView
from rest_framework_simplejwt.tokens import RefreshToken
from django.contrib.auth.base_user import BaseUserManager
from django.contrib.auth.hashers import make_password
Glenda Emanuella Sutanto's avatar
Glenda Emanuella Sutanto committed
7
8
9
10
from dietela_quiz.models import DietProfile
from dietela_quiz.serializers import DietProfileSerializer
from .models import CustomUser
from .serializers import CustomUserDetailsSerializer
11
from .google_utils import validate_google_token
Glenda Emanuella Sutanto's avatar
Glenda Emanuella Sutanto committed
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38


class LinkUserAndDietProfileViewSet(viewsets.ViewSet):

    @staticmethod
    def create(request):
        email = request.data['email']
        diet_profile_id = request.data['diet_profile_id']

        try:
            user = CustomUser.objects.get(email=email)
        except CustomUser.DoesNotExist:
            return Response({'message': 'User is not found.'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            diet_profile = DietProfile.objects.get(id=diet_profile_id)
        except DietProfile.DoesNotExist:
            return Response({'message': 'Diet profile is not found.'}, \
                status=status.HTTP_400_BAD_REQUEST)

        user.diet_profile = diet_profile
        user.save()

        return Response({\
            'user': CustomUserDetailsSerializer(user).data,\
            'diet_profile': DietProfileSerializer(diet_profile).data\
        }, status=status.HTTP_200_OK)
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62


class GoogleView(APIView):
    def post(self, request):
        success, google_data = validate_google_token(request.data.get('access_token'))
        if not success:
            return google_data
        try:
            user = CustomUser.objects.get(email=
                google_data
            )
        except CustomUser.DoesNotExist:
            user = CustomUser()
            # random default password
            user.password = make_password(BaseUserManager().make_random_password())
            user.email = google_data
            user.save()

        token = RefreshToken.for_user(user)  # generate token
        response = {}
        response['user'] = CustomUserDetailsSerializer(user).data
        response['access_token'] = str(token.access_token)
        response['refresh_token'] = str(token)
        return Response(response)