-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserializers.py
More file actions
292 lines (234 loc) · 9.23 KB
/
serializers.py
File metadata and controls
292 lines (234 loc) · 9.23 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
import uuid
import django.contrib.auth.password_validation
import django.db.transaction
import rest_framework.exceptions
import rest_framework.serializers
import rest_framework_simplejwt.exceptions
import rest_framework_simplejwt.serializers
import rest_framework_simplejwt.tokens
import business.constants
import business.models
import business.utils.tokens
import core.serializers
import core.utils.auth
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],
style={'input_type': 'password'},
min_length=business.constants.COMPANY_PASSWORD_MIN_LENGTH,
max_length=business.constants.COMPANY_PASSWORD_MAX_LENGTH,
)
name = rest_framework.serializers.CharField(
required=True,
min_length=business.constants.COMPANY_NAME_MIN_LENGTH,
max_length=business.constants.COMPANY_NAME_MAX_LENGTH,
)
email = rest_framework.serializers.EmailField(
required=True,
min_length=business.constants.COMPANY_EMAIL_MIN_LENGTH,
max_length=business.constants.COMPANY_EMAIL_MAX_LENGTH,
)
class Meta:
model = business.models.Company
fields = ('id', 'name', 'email', 'password')
@django.db.transaction.atomic
def create(self, validated_data):
try:
company = business.models.Company.objects.create_company(
**validated_data,
)
except django.db.IntegrityError:
exc = rest_framework.exceptions.APIException(
detail={
'email': 'This email address is already registered.',
},
)
exc.status_code = 409
raise exc
return core.utils.auth.bump_token_version(company)
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')
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',
)
attrs['company'] = company
return attrs
class CompanyTokenRefreshSerializer(
rest_framework_simplejwt.serializers.TokenRefreshSerializer,
):
def validate(self, attrs):
attrs = super().validate(attrs)
refresh = rest_framework_simplejwt.tokens.RefreshToken(
attrs['refresh'],
)
company = self.get_active_company_from_token(refresh)
company = core.utils.auth.bump_token_version(company)
return business.utils.tokens.generate_company_tokens(company)
def get_active_company_from_token(self, token):
if token.payload.get('user_type') != 'company':
raise rest_framework_simplejwt.exceptions.InvalidToken(
'This refresh endpoint is for company tokens only',
)
company_id = token.payload.get('company_id')
try:
company_uuid = uuid.UUID(company_id)
except (TypeError, ValueError):
raise rest_framework_simplejwt.exceptions.InvalidToken(
'Invalid or missing company_id in token',
)
try:
company = business.models.Company.objects.get(
id=company_uuid,
is_active=True,
)
except business.models.Company.DoesNotExist:
raise rest_framework_simplejwt.exceptions.InvalidToken(
'Company not found or inactive',
)
token_version = token.payload.get('token_version', 0)
if company.token_version != token_version:
raise rest_framework_simplejwt.exceptions.InvalidToken(
'Token is blacklisted',
)
return company
class MultiCountryField(rest_framework.serializers.ListField):
"""
Custom field for handling multiple country codes,
passed either as a comma-separated list or as multiple parameters.
"""
def __init__(self, **kwargs):
kwargs['child'] = core.serializers.CountryField()
kwargs['allow_empty'] = False
super().__init__(**kwargs)
def to_internal_value(self, data):
if (
isinstance(data, list)
and len(data) == 1
and isinstance(data[0], str)
):
data = [item.strip() for item in data[0].split(',')]
return super().to_internal_value(data)
class PromoCreateSerializer(core.serializers.BaseCompanyPromoSerializer):
url = rest_framework.serializers.HyperlinkedIdentityField(
view_name='api-business:promo-detail',
lookup_field='id',
)
class Meta(core.serializers.BaseCompanyPromoSerializer.Meta):
fields = (
'url',
) + core.serializers.BaseCompanyPromoSerializer.Meta.fields
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)
return business.models.Promo.objects.create_promo(
user=self.context['request'].user,
target_data=target_data,
promo_common=promo_common,
promo_unique=promo_unique,
**validated_data,
)
class PromoListQuerySerializer(
core.serializers.BaseLimitOffsetPaginationSerializer,
):
"""
Validates query parameters for the list of promotions.
"""
sort_by = rest_framework.serializers.ChoiceField(
choices=['active_from', 'active_until'],
required=False,
)
country = MultiCountryField(required=False)
def validate(self, attrs):
query_params = self.initial_data.keys()
allowed_params = self.fields.keys()
unexpected_params = set(query_params) - set(allowed_params)
if unexpected_params:
raise rest_framework.exceptions.ValidationError(
f'Invalid parameters: {", ".join(unexpected_params)}',
)
if 'country' in attrs:
attrs['countries'] = attrs.pop('country')
return attrs
class PromoDetailSerializer(core.serializers.BaseCompanyPromoSerializer):
promo_id = rest_framework.serializers.UUIDField(
source='id',
read_only=True,
)
company_name = rest_framework.serializers.CharField(
source='company.name',
read_only=True,
)
like_count = rest_framework.serializers.IntegerField(
source='get_like_count',
read_only=True,
)
comment_count = rest_framework.serializers.IntegerField(
source='get_comment_count',
read_only=True,
)
used_count = rest_framework.serializers.IntegerField(
source='get_used_codes_count',
read_only=True,
)
active = rest_framework.serializers.BooleanField(
source='is_active',
read_only=True,
)
promo_unique = rest_framework.serializers.SerializerMethodField()
class Meta(core.serializers.BaseCompanyPromoSerializer.Meta):
fields = core.serializers.BaseCompanyPromoSerializer.Meta.fields + (
'promo_id',
'company_name',
'like_count',
'comment_count',
'used_count',
'active',
)
def get_promo_unique(self, obj):
if obj.mode == business.constants.PROMO_MODE_UNIQUE:
return obj.get_available_unique_codes
return None
def update(self, instance, validated_data):
target_data = validated_data.pop('target', None)
instance = super().update(instance, validated_data)
if target_data is not None:
instance.target = target_data
instance.save(update_fields=['target'])
return instance
class PromoReadOnlySerializer(PromoDetailSerializer):
"""Read-only serializer for promo."""
company_id = rest_framework.serializers.UUIDField(
source='company.id',
read_only=True,
)
class Meta(PromoDetailSerializer.Meta):
fields = PromoDetailSerializer.Meta.fields + ('company_id',)
read_only_fields = fields
class CountryStatSerializer(rest_framework.serializers.Serializer):
"""Serializer for activation statistics by country."""
country = rest_framework.serializers.CharField()
activations_count = rest_framework.serializers.IntegerField()
class PromoStatSerializer(rest_framework.serializers.Serializer):
"""Serializer for overall promo code statistics."""
activations_count = rest_framework.serializers.IntegerField()
countries = CountryStatSerializer(many=True)