Coverage for apps/users/serializers.py: 93%
59 statements
« prev ^ index » next coverage.py v6.4.4, created at 2023-10-27 13:33 -0600
« prev ^ index » next coverage.py v6.4.4, created at 2023-10-27 13:33 -0600
1from django.conf import settings
2from django.contrib.auth.password_validation import validate_password
3from django.contrib.auth.tokens import PasswordResetTokenGenerator
4from rest_framework import serializers
5from rest_framework.validators import ValidationError
7from api.serializers import ToRepresentationMixin
9from .models import Employee, User
12class EmployeeSerializer(serializers.ModelSerializer):
13 """
14 Serializer for Employee
15 """
17 class Meta:
18 model = Employee
19 read_only_fields = ["user"]
20 fields = read_only_fields + ["name", "permissions"]
23class UserSerializer(ToRepresentationMixin):
24 """
25 Serializer for User
26 """
28 name = serializers.CharField(max_length=64, write_only=True)
29 permissions = serializers.ChoiceField(Employee.Permissions.choices, write_only=True)
31 REPRESENTATION_FIELDS = [["employee", EmployeeSerializer, False]]
33 class Meta:
34 model = User
35 read_only_fields = ["id", "employee"]
36 fields = read_only_fields + ["email", "name", "permissions"]
38 def create(self, validated_data):
39 name = validated_data.pop("name")
40 permissions = validated_data.pop("permissions")
41 user = super().create(validated_data)
42 Employee.objects.create(user=user, name=name, permissions=permissions)
43 return user
46class ResetPasswordSerializer(serializers.Serializer):
47 email = serializers.EmailField()
49 def validate_email(self, value):
50 try:
51 return User.objects.get(email=value)
52 except User.DoesNotExist:
53 raise serializers.ValidationError("No existe un usuario con ese email")
55 def save(self, validated_data):
56 email = validated_data.get("email")
57 user = User.objects.get(email=email)
58 token = PasswordResetTokenGenerator().make_token(user)
60 return f"{settings.FRONTEND_DOMAIN}{settings.FRONTEND_RESET_PASSWORD_PATH}/{token}?u={user.pk}", user
63class SetPasswordSerializer(serializers.Serializer):
64 """Serializer to set password"""
66 user_id = serializers.CharField()
67 token = serializers.CharField()
68 password = serializers.CharField()
70 def validate_password(self, value):
71 validate_password(value)
72 return value
74 def validate(self, attrs):
75 token = attrs.get("token")
76 user_id = attrs.get("user_id")
77 user = User.objects.get(pk=user_id)
78 verified_token = PasswordResetTokenGenerator().check_token(user, token)
79 if verified_token:
80 return attrs
81 else:
82 raise ValidationError({"token": "The token is not valid"})
84 def save(self, validated_data):
85 data = validated_data
86 user_id = data.get("user_id")
87 user = User.objects.get(pk=user_id)
88 user.set_password(data.get("password"))
89 user.save()