-
Notifications
You must be signed in to change notification settings - Fork 24
/
serializers.py
197 lines (156 loc) · 5.9 KB
/
serializers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
from django.contrib.auth import authenticate, get_user_model
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
from rest_framework.authtoken.serializers import (
AuthTokenSerializer as DRFAuthTokenSerializer
)
from user_management.utils.validators import validate_password_strength
User = get_user_model()
class ValidateEmailMixin(object):
def validate_email(self, attrs, source):
email = attrs.get(source).lower()
try:
User.objects.get_by_natural_key(email)
except User.DoesNotExist:
attrs[source] = email
return attrs
else:
msg = _('That email address has already been registered.')
raise serializers.ValidationError(msg)
class EmailSerializerBase(serializers.Serializer):
email = serializers.EmailField(max_length=511, label=_('Email address'))
class Meta:
fields = ['email']
class AuthTokenSerializer(DRFAuthTokenSerializer):
"""
Fix DRF's error messages (which ain't very helpful).
Also, end the indentation nonsense.
"""
def validate(self, attrs):
username = attrs.get('username')
password = attrs.get('password')
user = authenticate(username=username, password=password)
if not user:
msg = _('Unable to log in with provided credentials.')
raise serializers.ValidationError(msg)
attrs['user'] = user
return attrs
class RegistrationSerializer(ValidateEmailMixin, serializers.ModelSerializer):
password = serializers.CharField(
write_only=True,
min_length=8,
label=_('Password'),
validators=[validate_password_strength],
)
password2 = serializers.CharField(
write_only=True,
min_length=8,
label=_('Repeat password'),
)
class Meta:
fields = ['name', 'email', 'password', 'password2']
model = User
def validate_password2(self, attrs, source):
password2 = attrs.pop(source)
if password2 != attrs.get('password'):
msg = _('Your passwords do not match.')
raise serializers.ValidationError(msg)
return attrs
def restore_object(self, attrs, instance=None):
password = attrs.pop('password')
instance = super(RegistrationSerializer, self).restore_object(attrs, instance)
instance.set_password(password)
return instance
class PasswordChangeSerializer(serializers.ModelSerializer):
old_password = serializers.CharField(
write_only=True,
label=_('Old password'),
)
new_password = serializers.CharField(
write_only=True,
min_length=8,
label=_('New password'),
validators=[validate_password_strength],
)
new_password2 = serializers.CharField(
write_only=True,
min_length=8,
label=_('Repeat new password'),
)
class Meta:
model = User
fields = ('old_password', 'new_password', 'new_password2')
def restore_object(self, attrs, instance=None):
instance = super(PasswordChangeSerializer, self).restore_object(
attrs,
instance,
)
instance.set_password(attrs['new_password'])
return instance
def validate_old_password(self, attrs, source):
value = attrs[source]
if not self.object.check_password(value):
msg = _('Invalid password.')
raise serializers.ValidationError(msg)
return attrs
def validate_new_password2(self, attrs, source):
if attrs.get('new_password') != attrs[source]:
msg = _('Your new passwords do not match.')
raise serializers.ValidationError(msg)
return attrs
class PasswordResetSerializer(serializers.ModelSerializer):
new_password = serializers.CharField(
write_only=True,
min_length=8,
label=_('New password'),
validators=[validate_password_strength],
)
new_password2 = serializers.CharField(
write_only=True,
min_length=8,
label=_('Repeat new password'),
)
class Meta:
model = User
fields = ('new_password', 'new_password2')
def restore_object(self, attrs, instance=None):
instance = super(PasswordResetSerializer, self).restore_object(
attrs,
instance,
)
instance.set_password(attrs['new_password'])
return instance
def validate_new_password2(self, attrs, source):
if attrs.get('new_password') != attrs[source]:
msg = _('Your new passwords do not match.')
raise serializers.ValidationError(msg)
return attrs
class PasswordResetEmailSerializer(EmailSerializerBase):
pass
class ProfileSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('name', 'email', 'date_joined')
read_only_fields = ('email', 'date_joined')
class ResendConfirmationEmailSerializer(EmailSerializerBase):
def validate_email(self, attrs, source):
"""Check if user exists and email_verification_required."""
email = attrs[source]
try:
self.user = User.objects.get_by_natural_key(email)
except User.DoesNotExist:
msg = _('A user with this email address does not exist.')
raise serializers.ValidationError(msg)
if not self.user.email_verification_required:
msg = _('User email address is already verified.')
raise serializers.ValidationError(msg)
return attrs
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'name', 'email', 'date_joined')
read_only_fields = ('email', 'date_joined')
view_name = 'user_management_api:user_detail'
class UserSerializerCreate(ValidateEmailMixin, UserSerializer):
class Meta(UserSerializer.Meta):
read_only_fields = ('date_joined',)