Fakultas Ilmu Komputer UI

serializers.py 2.01 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

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

Kefas Satrio Bangkit Solidedantyo's avatar
Kefas Satrio Bangkit Solidedantyo committed
10
11
12
13
    def to_representation(self, instance):
        result = super().to_representation(instance)
        if instance.groups.exists():
            result['role'] = instance.groups.first().name
14
15
        if instance.is_staff:
            result['role'] = 'admin'
Kefas Satrio Bangkit Solidedantyo's avatar
Kefas Satrio Bangkit Solidedantyo committed
16
17
        return result

Glenda Emanuella Sutanto's avatar
Glenda Emanuella Sutanto committed
18
19
    class Meta:
        model = CustomUser
20
21
        fields = ('id', 'name', 'email',)
        read_only_fields = ('id', 'email',)
Kefas Satrio Bangkit Solidedantyo's avatar
Kefas Satrio Bangkit Solidedantyo committed
22

23

Kefas Satrio Bangkit Solidedantyo's avatar
Kefas Satrio Bangkit Solidedantyo committed
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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):
        pass

    def update(self, instance, validated_data):
        pass
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65


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):
        pass

    def update(self, instance, validated_data):
        pass

    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