22from rest_framework .serializers import ModelSerializer
33from django .contrib .auth .models import User
44from django .contrib .auth .password_validation import validate_password
5+ from django .contrib .auth import authenticate
6+ from rest_framework_simplejwt .tokens import RefreshToken
7+ from rest_framework .exceptions import AuthenticationFailed
58
69from .models import Todo
710
@@ -15,34 +18,103 @@ class Meta:
1518class TodoDetailSerializer (ModelSerializer ):
1619 class Meta :
1720 model = Todo
18- fields = "__all__"
21+ fields = [ "id" , "title" , "description" , "completed" ]
1922
2023
21- class RegisterSerializer (ModelSerializer ):
22- password2 = serializers .CharField (
24+ class RegisterSerializer (serializers .Serializer ):
25+ # password2 = serializers.CharField(
26+ # write_only=True, required=True, style={"input_type": "password"}
27+ # )
28+ name = serializers .CharField (required = True , write_only = True )
29+ email = serializers .EmailField (required = True )
30+ password = serializers .CharField (
2331 write_only = True , required = True , style = {"input_type" : "password" }
2432 )
2533
26- class Meta :
27- model = User
28- fields = ["username" , "email" , "password" , "password2" ]
29- extra_kwargs = {
30- "password" : {"write_only" : True , "style" : {"input_type" : "password" }},
31- "email" : {"required" : True },
32- "username" : {"required" : True },
33- }
34+ # class Meta:
35+ # model = User
36+ # fields = [
37+ # # "name",
38+ # "email",
39+ # "password",
40+ # # "password2",
41+ # ]
42+ # extra_kwargs = {
43+ # "password": {"write_only": True, "style": {"input_type": "password"}},
44+ # "email": {"required": True},
45+ # # "name": {"required": True},
46+ # }
3447
3548 def create (self , validated_data ):
36- user = User .objects .create (
37- username = validated_data ["username " ],
49+ user = User .objects .create_user (
50+ username = validated_data ["email " ],
3851 email = validated_data ["email" ],
3952 password = validated_data ["password" ],
53+ first_name = validated_data ["name" ],
4054 )
4155 return user
4256
57+ def validate_email (self , value ):
58+ email_lower = value .lower ()
59+ if User .objects .filter (username = email_lower ).exists ():
60+ raise serializers .ValidationError ("A user with this email already exists." )
61+ return value
62+
63+ def to_representation (self , instance ):
64+ return {
65+ "name" : instance .first_name ,
66+ "email" : instance .email ,
67+ }
68+
69+ # def validate(self, attrs):
70+ # password2 = attrs.pop("password2")
71+ # if attrs["password"] != password2:
72+ # raise serializers.ValidationError({"password": "Passwords do not match."})
73+ # validate_password(attrs["password"], user=User(username=attrs["username"]))
74+ # return attrs
75+
76+
77+ # add email serializer to make user login with email and password
78+ class EmailLoginSerializer (ModelSerializer ):
79+ class Meta :
80+ model = User
81+ fields = ["email" , "password" ]
82+
83+ email = serializers .EmailField (required = True )
84+ password = serializers .CharField (required = True , write_only = True )
85+
4386 def validate (self , attrs ):
44- password2 = attrs .pop ("password2" )
45- if attrs ["password" ] != password2 :
46- raise serializers .ValidationError ({"password" : "Passwords do not match." })
47- validate_password (attrs ["password" ], user = User (username = attrs ["username" ]))
48- return attrs
87+ email = attrs .get ("email" )
88+ password = attrs .get ("password" )
89+
90+ if not email or not password :
91+ raise AuthenticationFailed ("Email and password are required." )
92+
93+ user = authenticate (email = email , password = password )
94+
95+ # Find the user by their email
96+ # try:
97+ # user = User.objects.get(email=email)
98+ # except User.DoesNotExist:
99+ # raise AuthenticationFailed(
100+ # "No active account found with the given credentials"
101+ # )
102+
103+ # Authentication
104+ authenticated_user = authenticate (username = email , password = password )
105+
106+ if not authenticated_user :
107+ raise AuthenticationFailed (
108+ "No active account found with the given credentials"
109+ )
110+
111+ if not authenticated_user .is_active :
112+ raise AuthenticationFailed ("User account is disabled." )
113+
114+ refresh = RefreshToken .for_user (authenticated_user )
115+
116+ return {
117+ "refresh" : str (refresh ),
118+ "access" : str (refresh .access_token ),
119+ "user" : authenticated_user ,
120+ }
0 commit comments