-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserializers.py
More file actions
363 lines (316 loc) · 11.2 KB
/
serializers.py
File metadata and controls
363 lines (316 loc) · 11.2 KB
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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
import uuid
import django.contrib.auth.password_validation
import django.core.exceptions
import django.core.validators
import pycountry
import rest_framework.exceptions
import rest_framework.serializers
import rest_framework.status
import rest_framework_simplejwt.exceptions
import rest_framework_simplejwt.serializers
import rest_framework_simplejwt.tokens
import rest_framework_simplejwt.views
import business.models as business_models
import business.validators
class CompanySignUpSerializer(rest_framework.serializers.ModelSerializer):
id = rest_framework.serializers.UUIDField(read_only=True)
password = rest_framework.serializers.CharField(
write_only=True,
required=True,
validators=[django.contrib.auth.password_validation.validate_password],
min_length=8,
max_length=60,
style={'input_type': 'password'},
)
name = rest_framework.serializers.CharField(
required=True,
min_length=5,
max_length=50,
)
email = rest_framework.serializers.EmailField(
required=True,
min_length=8,
max_length=120,
validators=[
business.validators.UniqueEmailValidator(
'This email address is already registered.',
'email_conflict',
),
],
)
class Meta:
model = business_models.Company
fields = (
'id',
'name',
'email',
'password',
)
def create(self, validated_data):
try:
company = business_models.Company.objects.create_company(
email=validated_data['email'],
name=validated_data['name'],
password=validated_data['password'],
)
company.token_version += 1
company.save()
return company
except django.core.exceptions.ValidationError as e:
raise rest_framework.serializers.ValidationError(e.messages)
class CompanySignInSerializer(
rest_framework.serializers.Serializer,
):
email = rest_framework.serializers.EmailField(required=True)
password = rest_framework.serializers.CharField(
required=True,
write_only=True,
style={'input_type': 'password'},
)
def validate(self, attrs):
email = attrs.get('email')
password = attrs.get('password')
if not email or not password:
raise rest_framework.exceptions.ValidationError(
{'detail': 'Both email and password are required'},
code='required',
)
try:
company = business_models.Company.objects.get(email=email)
except business_models.Company.DoesNotExist:
raise rest_framework.serializers.ValidationError(
'Invalid credentials',
)
if not company.is_active or not company.check_password(password):
raise rest_framework.exceptions.AuthenticationFailed(
{'detail': 'Invalid credentials or inactive account'},
code='authentication_failed',
)
return attrs
class CompanyTokenRefreshSerializer(
rest_framework_simplejwt.serializers.TokenRefreshSerializer,
):
def validate(self, attrs):
refresh = rest_framework_simplejwt.tokens.RefreshToken(
attrs['refresh'],
)
user_type = refresh.payload.get('user_type', 'user')
if user_type != 'company':
raise rest_framework_simplejwt.exceptions.InvalidToken(
'This refresh endpoint is for company tokens only',
)
company_id = refresh.payload.get('company_id')
if not company_id:
raise rest_framework_simplejwt.exceptions.InvalidToken(
'Company ID missing in token',
)
try:
company = business_models.Company.objects.get(
id=uuid.UUID(company_id),
)
except business_models.Company.DoesNotExist:
raise rest_framework_simplejwt.exceptions.InvalidToken(
'Company not found',
)
token_version = refresh.payload.get('token_version', 0)
if company.token_version != token_version:
raise rest_framework_simplejwt.exceptions.InvalidToken(
'Token is blacklisted',
)
new_refresh = rest_framework_simplejwt.tokens.RefreshToken()
new_refresh['user_type'] = 'company'
new_refresh['company_id'] = str(company.id)
new_refresh['token_version'] = company.token_version
return {
'access': str(new_refresh.access_token),
'refresh': str(new_refresh),
}
class TargetSerializer(rest_framework.serializers.Serializer):
age_from = rest_framework.serializers.IntegerField(
min_value=0,
max_value=100,
required=False,
allow_null=True,
)
age_until = rest_framework.serializers.IntegerField(
min_value=0,
max_value=100,
required=False,
allow_null=True,
)
country = rest_framework.serializers.CharField(
max_length=2,
min_length=2,
required=False,
allow_null=True,
allow_blank=True,
)
categories = rest_framework.serializers.ListField(
child=rest_framework.serializers.CharField(
min_length=2,
max_length=20,
),
max_length=20,
required=False,
allow_empty=True,
)
def validate(self, data):
age_from = data.get('age_from')
age_until = data.get('age_until')
if (
age_from is not None
and age_until is not None
and age_from > age_until
):
raise rest_framework.serializers.ValidationError(
{'age_until': 'Must be greater than or equal to age_from.'},
)
country = data.get('country')
if country:
country = country.strip().upper()
try:
pycountry.countries.lookup(country)
data['country'] = country
except LookupError:
raise rest_framework.serializers.ValidationError(
{'country': 'Invalid ISO 3166-1 alpha-2 country code.'},
)
return data
class PromoCreateSerializer(rest_framework.serializers.ModelSerializer):
description = rest_framework.serializers.CharField(
min_length=10,
max_length=300,
required=True,
)
image_url = rest_framework.serializers.CharField(
required=False,
max_length=350,
validators=[
django.core.validators.URLValidator(schemes=['http', 'https']),
],
)
target = TargetSerializer(required=True)
promo_common = rest_framework.serializers.CharField(
min_length=5,
max_length=30,
required=False,
allow_null=True,
)
promo_unique = rest_framework.serializers.ListField(
child=rest_framework.serializers.CharField(
min_length=3,
max_length=30,
),
min_length=1,
max_length=5000,
required=False,
allow_null=True,
)
class Meta:
model = business_models.Promo
fields = (
'description',
'image_url',
'target',
'max_count',
'active_from',
'active_until',
'mode',
'promo_common',
'promo_unique',
)
def validate(self, data):
mode = data.get('mode')
promo_common = data.get('promo_common')
promo_unique = data.get('promo_unique')
max_count = data.get('max_count')
if mode == business_models.Promo.MODE_COMMON:
if not promo_common:
raise rest_framework.serializers.ValidationError(
{
'promo_common': (
'This field is required for COMMON mode.'
),
},
)
if promo_unique is not None:
raise rest_framework.serializers.ValidationError(
{
'promo_unique': (
'This field is not allowed for COMMON mode.'
),
},
)
if max_count < 0 or max_count > 100000000:
raise rest_framework.serializers.ValidationError(
{
'max_count': (
'Must be between 0 and 100,000,000 '
'for COMMON mode.'
),
},
)
elif mode == business_models.Promo.MODE_UNIQUE:
if not promo_unique:
raise rest_framework.serializers.ValidationError(
{
'promo_unique': (
'This field is required for UNIQUE mode.'
),
},
)
if promo_common is not None:
raise rest_framework.serializers.ValidationError(
{
'promo_common': (
'This field is not allowed for UNIQUE mode.'
),
},
)
if max_count != 1:
raise rest_framework.serializers.ValidationError(
{'max_count': 'Must be 1 for UNIQUE mode.'},
)
else:
raise rest_framework.serializers.ValidationError(
{'mode': 'Invalid mode.'},
)
active_from = data.get('active_from')
active_until = data.get('active_until')
if active_from and active_until and active_from > active_until:
raise rest_framework.serializers.ValidationError(
{'active_until': 'Must be after or equal to active_from.'},
)
return data
def create(self, validated_data):
target_data = validated_data.pop('target')
promo_common = validated_data.pop('promo_common', None)
promo_unique = validated_data.pop('promo_unique', None)
mode = validated_data['mode']
user = self.context['request'].user
validated_data['company'] = user
promo = business_models.Promo.objects.create(
**validated_data,
target=target_data,
)
if mode == business_models.Promo.MODE_COMMON:
promo.promo_common = promo_common
promo.save()
elif mode == business_models.Promo.MODE_UNIQUE and promo_unique:
promo_codes = [
business_models.PromoCode(promo=promo, code=code)
for code in promo_unique
]
business_models.PromoCode.objects.bulk_create(promo_codes)
return promo
def to_representation(self, instance):
data = super().to_representation(instance)
data['target'] = instance.target
if instance.mode == business_models.Promo.MODE_UNIQUE:
data['promo_unique'] = [
code.code for code in instance.unique_codes.all()
]
data.pop('promo_common', None)
else:
data.pop('promo_unique', None)
return data