Fakultas Ilmu Komputer UI

serializers.py 4 KB
Newer Older
1
import datetime
2
from django.contrib.auth.models import Group
Kefas Satrio Bangkit Solidedantyo's avatar
Kefas Satrio Bangkit Solidedantyo committed
3
4
from rest_framework import serializers, exceptions
from dj_rest_auth.serializers import LoginSerializer
5
from dj_rest_auth.registration.serializers import RegisterSerializer
Glenda Emanuella Sutanto's avatar
Glenda Emanuella Sutanto committed
6
7
from .models import CustomUser

8

9
class UserAuthSerializer(serializers.ModelSerializer):
Glenda Emanuella Sutanto's avatar
Glenda Emanuella Sutanto committed
10

Kefas Satrio Bangkit Solidedantyo's avatar
Kefas Satrio Bangkit Solidedantyo committed
11
12
    def to_representation(self, instance):
        result = super().to_representation(instance)
13
14

        result['is_finished_onboarding'] = True
Kefas Satrio Bangkit Solidedantyo's avatar
Kefas Satrio Bangkit Solidedantyo committed
15
16
        if instance.groups.exists():
            result['role'] = instance.groups.first().name
17
18
19
20
21
22
23
            if result['role'] == 'client':
                if hasattr(instance, 'diet_questionnaire'):
                    result['is_finished_onboarding'] = \
                        (len(instance.diet_questionnaire.finished_steps) == 6)
                else:
                    result['is_finished_onboarding'] = False

24
25
        if instance.is_staff:
            result['role'] = 'admin'
26

27
28
29
        result['transaction_status'] = None
        result['cart_id'] = None

30
        if instance.cart.exists():
31
32
33
34
35
            active_carts = instance.cart.filter(program_end_date__gte=datetime.date.today())
            if len(active_carts) > 0:
                last_active_cart = active_carts.order_by('-id')[0]
                result['transaction_status'] = last_active_cart.transaction_status
                result['cart_id'] = last_active_cart.id
36

37
38
39
40
41
42
43
44
        result['nutritionist'] = None

        if instance.nutritionist is not None:
            result['nutritionist'] = {
                'full_name_and_degree': instance.nutritionist.full_name_and_degree,
                'phone_number': instance.nutritionist.phone_number
            }

45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
        return result

    class Meta:
        model = CustomUser
        fields = ('id', 'name', 'email',)
        read_only_fields = ('id', 'email',)


class CustomUserDetailsSerializer(serializers.ModelSerializer):

    def to_representation(self, instance):
        result = super().to_representation(instance)
        if instance.groups.exists():
            result['role'] = instance.groups.first().name
        if instance.is_staff:
            result['role'] = 'admin'
Kefas Satrio Bangkit Solidedantyo's avatar
Kefas Satrio Bangkit Solidedantyo committed
61
62
        return result

Glenda Emanuella Sutanto's avatar
Glenda Emanuella Sutanto committed
63
64
    class Meta:
        model = CustomUser
65
66
        fields = ('id', 'name', 'email','deadline')
        read_only_fields = ('id', 'email','deadline')
Kefas Satrio Bangkit Solidedantyo's avatar
Kefas Satrio Bangkit Solidedantyo committed
67

68

Kefas Satrio Bangkit Solidedantyo's avatar
Kefas Satrio Bangkit Solidedantyo committed
69
70
71
72
73
74
75
76
77
78
79
80
class CustomLoginSerializer(LoginSerializer):

    def validate_auth_user_status(self, user):
        request = self.context.get('request')
        if not request.data.get('role'):
            msg = 'Role is missing from the payload.'
            raise exceptions.ValidationError(msg)
        if not user.groups.filter(name=request.data.get('role')).exists():
            msg = 'Invalid role for the user.'
            raise exceptions.ValidationError(msg)

    def create(self, validated_data):
81
82
        pass    # Empty because the function is not needed
                # but Pylint demanded to implement it anyway
Kefas Satrio Bangkit Solidedantyo's avatar
Kefas Satrio Bangkit Solidedantyo committed
83
84

    def update(self, instance, validated_data):
85
86
        pass    # Empty because the function is not needed
                # but Pylint demanded to implement it anyway
87
88
89
90
91
92
93
94
95
96
97
98
99
100


class CustomRegisterSerializer(RegisterSerializer):
    name = serializers.CharField()

    def get_cleaned_data(self):
        super().get_cleaned_data()
        return {
            'email': self.validated_data.get('email', ''),
            'password1': self.validated_data.get('password1', ''),
            'name': self.validated_data.get('name', '')
        }

    def create(self, validated_data):
101
102
        pass    # Empty because the function is not needed
                # but Pylint demanded to implement it anyway
103
104

    def update(self, instance, validated_data):
105
106
        pass    # Empty because the function is not needed
                # but Pylint demanded to implement it anyway
107
108
109
110
111
112
113
114

    def save(self, request):
        user = super().save(request)
        user.name = self.get_cleaned_data().get('name')
        user.save()
        client_role, _created = Group.objects.get_or_create(name='client')
        user.groups.add(client_role)
        return user