Coverage for users/serializers.py: 62%
51 statements
« prev ^ index » next coverage.py v6.4.4, created at 2022-11-04 10:09 -0600
« prev ^ index » next coverage.py v6.4.4, created at 2022-11-04 10:09 -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
6from .models import User
9class UserSerializer(serializers.ModelSerializer):
10 class Meta:
11 model = User
12 read_only_fields = ["id"]
13 fields = read_only_fields + [
14 "name",
15 "email",
16 "phone",
17 "first_name",
18 "last_name",
19 ]
22class RegisterSerializer(serializers.ModelSerializer):
23 password = serializers.CharField()
25 class Meta:
26 model = User
27 fields = ["first_name", "last_name", "email", "password", "phone"]
29 def create(self, validated_data):
30 return User.objects.create_user(**validated_data)
33class ResetPasswordSerializer(serializers.Serializer):
34 email = serializers.EmailField()
36 def validate_email(self, value):
37 try:
38 return User.objects.get(email=value)
39 except User.DoesNotExist:
40 raise serializers.ValidationError("No existe un usuario con ese email")
42 def save(self, validated_data):
43 email = validated_data.get("email")
44 user = User.objects.get(email=email)
45 token = PasswordResetTokenGenerator().make_token(user)
46 return f"{settings.FRONTEND_DOMAIN}/reset-password/{token}?u={user.pk}", user
49class SetPasswordSerializer(serializers.Serializer):
50 """Serializer to set password"""
52 user_id = serializers.CharField()
53 token = serializers.CharField()
54 password = serializers.CharField()
56 def validate_password(self, value):
57 validate_password(value)
58 return value
60 def validate(self, attrs):
61 token = attrs.get("token")
62 user_id = attrs.get("user_id")
63 user = User.objects.get(pk=user_id)
64 verified_token = PasswordResetTokenGenerator().check_token(user, token)
65 if verified_token:
66 return attrs
67 else:
68 raise ValidationError({"token": "The token is not valid"})
70 def save(self, validated_data):
71 data = self.validated_data
72 user_id = data.get("user_id")
73 user = User.objects.get(pk=user_id)
74 user.set_password(data.get("password"))
75 user.save()