Fakultas Ilmu Komputer UI

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

7

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

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

        result['is_finished_onboarding'] = True
Kefas Satrio Bangkit Solidedantyo's avatar
Kefas Satrio Bangkit Solidedantyo committed
14
15
        if instance.groups.exists():
            result['role'] = instance.groups.first().name
16
17
18
19
20
21
22
            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

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

26
        if instance.cart.exists():
27
            result['transaction_status'] = instance.cart.last().transaction_status
28
            result['cart_id'] = instance.cart.last().id
29
        else:
30
            result['transaction_status'] = None
31
            result['cart_id'] = None
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48

        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
49
50
        return result

Glenda Emanuella Sutanto's avatar
Glenda Emanuella Sutanto committed
51
52
    class Meta:
        model = CustomUser
53
54
        fields = ('id', 'name', 'email',)
        read_only_fields = ('id', 'email',)
Kefas Satrio Bangkit Solidedantyo's avatar
Kefas Satrio Bangkit Solidedantyo committed
55

56

Kefas Satrio Bangkit Solidedantyo's avatar
Kefas Satrio Bangkit Solidedantyo committed
57
58
59
60
61
62
63
64
65
66
67
68
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):
69
70
        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
71
72

    def update(self, instance, validated_data):
73
74
        pass    # Empty because the function is not needed
                # but Pylint demanded to implement it anyway
75
76
77
78
79
80
81
82
83
84
85
86
87
88


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):
89
90
        pass    # Empty because the function is not needed
                # but Pylint demanded to implement it anyway
91
92

    def update(self, instance, validated_data):
93
94
        pass    # Empty because the function is not needed
                # but Pylint demanded to implement it anyway
95
96
97
98
99
100
101
102

    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