-
Notifications
You must be signed in to change notification settings - Fork 993
Expand file tree
/
Copy pathserializer.py
More file actions
756 lines (604 loc) · 21.9 KB
/
serializer.py
File metadata and controls
756 lines (604 loc) · 21.9 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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
import re
from drf_spectacular.utils import extend_schema_field
from rest_framework import serializers
from rest_framework_simplejwt.tokens import RefreshToken
from disposable_email_domains import blocklist as disposable_domains
from common.utils import CURRENCY_SYMBOLS
from common.models import (
Activity,
Address,
APISettings,
Attachments,
Comment,
Document,
Org,
Profile,
Tags,
Teams,
User,
)
class OrgAwareRefreshToken(RefreshToken):
"""
Custom RefreshToken that includes org context in the token payload.
This ensures the org context is cryptographically signed and cannot be
forged by the client. The middleware should validate org_id from this
token instead of trusting the org header.
Embedded claims (to avoid extra API calls):
- org_id: Organization UUID
- org_name: Organization name (for display)
- role: User's role in the org (ADMIN/USER)
- org_settings: Currency and locale settings
"""
@classmethod
def for_user_and_org(cls, user, org, profile=None):
"""
Generate a refresh token for a user with org context.
Args:
user: User instance
org: Org instance or org_id UUID
profile: Optional Profile instance for role
Returns:
OrgAwareRefreshToken with org claims
"""
token = cls.for_user(user)
# Add user info to token (avoids extra API calls for display)
if user:
token["user_email"] = user.email
# Build display name from email (User model doesn't have first/last name)
token["user_name"] = user.email.split("@")[0] if user.email else ""
token["user_profile_pic"] = user.profile_pic or ""
# Add org context to the token payload
if org:
org_id = str(org.id) if hasattr(org, "id") else str(org)
token["org_id"] = org_id
# Add org_name for display (avoids /api/auth/profile call)
if hasattr(org, "name"):
token["org_name"] = org.name
# Add org settings for currency/locale
if hasattr(org, "default_currency"):
token["org_settings"] = {
"default_currency": org.default_currency or "USD",
"currency_symbol": CURRENCY_SYMBOLS.get(
org.default_currency or "USD", "$"
),
"default_country": org.default_country,
}
# Add role if profile provided (avoids /api/auth/profile call)
if profile:
token["role"] = profile.role
return token
class OrganizationSerializer(serializers.ModelSerializer):
class Meta:
model = Org
fields = ("id", "name", "api_key")
class OrgSettingsSerializer(serializers.ModelSerializer):
"""Serializer for org settings (currency, country, locale, company profile)"""
currency_symbol = serializers.SerializerMethodField()
logo_url = serializers.SerializerMethodField()
class Meta:
model = Org
fields = [
"id",
"name",
# Company profile
"company_name",
"logo",
"logo_url",
"address_line",
"city",
"state",
"postcode",
"country",
"phone",
"email",
"website",
"tax_id",
# Locale settings
"default_currency",
"default_country",
"currency_symbol",
]
read_only_fields = ["id", "currency_symbol", "logo_url"]
@extend_schema_field(str)
def get_currency_symbol(self, obj):
return CURRENCY_SYMBOLS.get(obj.default_currency or "USD", "$")
@extend_schema_field(str)
def get_logo_url(self, obj):
if obj.logo:
request = self.context.get("request")
if request:
return request.build_absolute_uri(obj.logo.url)
return obj.logo.url
return None
class TagsSerializer(serializers.ModelSerializer):
class Meta:
model = Tags
fields = (
"id",
"name",
"slug",
"color",
"description",
"is_active",
"created_at",
)
read_only_fields = ("id", "slug", "created_at")
class SocialLoginSerializer(serializers.Serializer):
token = serializers.CharField()
class CommentSerializer(serializers.ModelSerializer):
"""Serializer for Comment model using ContentType"""
content_type = serializers.SlugRelatedField(slug_field="model", read_only=True)
class Meta:
model = Comment
fields = (
"id",
"comment",
"commented_on",
"commented_by",
"content_type",
"object_id",
"org",
)
class CommentCreateSerializer(serializers.ModelSerializer):
"""Serializer for creating comments with ContentType"""
content_type = serializers.CharField(write_only=True)
object_id = serializers.UUIDField(write_only=True)
class Meta:
model = Comment
fields = (
"comment",
"content_type",
"object_id",
)
def create(self, validated_data):
from django.contrib.contenttypes.models import ContentType
content_type_str = validated_data.pop("content_type")
try:
content_type = ContentType.objects.get(model=content_type_str.lower())
except ContentType.DoesNotExist as exc:
raise serializers.ValidationError(
f"Invalid content type: {content_type_str}"
) from exc
validated_data["content_type"] = content_type
return super().create(validated_data)
class CommentUserSerializer(serializers.ModelSerializer):
"""Simplified user serializer for comments"""
user_details = serializers.SerializerMethodField()
class Meta:
model = Profile
fields = ("id", "user_details")
def get_user_details(self, obj):
if obj.user:
return {"email": obj.user.email, "profile_pic": obj.user.profile_pic}
return None
class LeadCommentSerializer(serializers.ModelSerializer):
"""Comment serializer with user details for display"""
commented_by = CommentUserSerializer(read_only=True)
class Meta:
model = Comment
fields = (
"id",
"comment",
"commented_on",
"commented_by",
)
class OrgProfileCreateSerializer(serializers.ModelSerializer):
"""
It is for creating organization
"""
name = serializers.CharField(max_length=255)
class Meta:
model = Org
fields = ["name"]
extra_kwargs = {"name": {"required": True}}
def validate_name(self, name):
if bool(re.search(r"[~\!@#\$%\^&\*\(\)\+{}\":;'/\[\]]", name)):
raise serializers.ValidationError(
"organization name should not contain any special characters"
)
if Org.objects.filter(name=name).exists():
raise serializers.ValidationError(
"Organization already exists with this name"
)
return name
class ShowOrganizationListSerializer(serializers.ModelSerializer):
"""
we are using it for show orjanization list
"""
org = OrganizationSerializer()
class Meta:
model = Profile
fields = (
"role",
"alternate_phone",
"has_sales_access",
"has_marketing_access",
"is_organization_admin",
"org",
)
class BillingAddressSerializer(serializers.ModelSerializer):
class Meta:
model = Address
fields = ("address_line", "street", "city", "state", "postcode", "country")
def __init__(self, *args, **kwargs):
account_view = kwargs.pop("account", False)
super().__init__(*args, **kwargs)
if account_view:
self.fields["address_line"].required = True
self.fields["street"].required = True
self.fields["city"].required = True
self.fields["state"].required = True
self.fields["postcode"].required = True
self.fields["country"].required = True
class CreateUserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = (
"email",
"profile_pic",
)
def __init__(self, *args, **kwargs):
self.org = kwargs.pop("org", None)
super().__init__(*args, **kwargs)
self.fields["email"].required = True
def validate_email(self, email):
if self.instance:
if self.instance.email != email:
if not Profile.objects.filter(user__email=email, org=self.org).exists():
return email
raise serializers.ValidationError("Email already exists")
return email
if not Profile.objects.filter(user__email=email.lower(), org=self.org).exists():
return email
raise serializers.ValidationError("Given Email id already exists")
class CreateProfileSerializer(serializers.ModelSerializer):
class Meta:
model = Profile
fields = (
"role",
"phone",
"alternate_phone",
"has_sales_access",
"has_marketing_access",
"is_organization_admin",
)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["alternate_phone"].required = False
self.fields["role"].required = True
self.fields["phone"].required = True
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ["id", "email", "profile_pic"]
class ProfileSerializer(serializers.ModelSerializer):
# address = BillingAddressSerializer()
user_details = serializers.SerializerMethodField()
@extend_schema_field(dict)
def get_user_details(self, obj):
return obj.user_details
class Meta:
model = Profile
fields = (
"id",
"user_details",
"role",
"address",
"has_marketing_access",
"has_sales_access",
"phone",
"date_of_joining",
"is_active",
"created_at",
)
class AttachmentsSerializer(serializers.ModelSerializer):
"""Serializer for Attachments model using ContentType"""
file_path = serializers.SerializerMethodField()
content_type = serializers.SlugRelatedField(slug_field="model", read_only=True)
@extend_schema_field(str)
def get_file_path(self, obj):
if obj.attachment:
return obj.attachment.url
return None
class Meta:
model = Attachments
fields = [
"id",
"created_by",
"file_name",
"created_at",
"file_path",
"content_type",
"object_id",
"org",
]
class AttachmentsCreateSerializer(serializers.ModelSerializer):
"""Serializer for creating attachments with ContentType"""
content_type = serializers.CharField(write_only=True)
object_id = serializers.UUIDField(write_only=True)
class Meta:
model = Attachments
fields = (
"file_name",
"attachment",
"content_type",
"object_id",
)
def create(self, validated_data):
from django.contrib.contenttypes.models import ContentType
content_type_str = validated_data.pop("content_type")
try:
content_type = ContentType.objects.get(model=content_type_str.lower())
except ContentType.DoesNotExist as exc:
raise serializers.ValidationError(
f"Invalid content type: {content_type_str}"
) from exc
validated_data["content_type"] = content_type
return super().create(validated_data)
class DocumentSerializer(serializers.ModelSerializer):
shared_to = ProfileSerializer(read_only=True, many=True)
teams = serializers.SerializerMethodField()
created_by = UserSerializer()
org = OrganizationSerializer()
@extend_schema_field(list)
def get_teams(self, obj):
return obj.teams.all().values()
class Meta:
model = Document
fields = [
"id",
"title",
"document_file",
"status",
"shared_to",
"teams",
"created_at",
"created_by",
"org",
]
class DocumentCreateSerializer(serializers.ModelSerializer):
def __init__(self, *args, **kwargs):
request_obj = kwargs.pop("request_obj", None)
super().__init__(*args, **kwargs)
self.fields["title"].required = True
self.org = request_obj.profile.org
def validate_title(self, title):
if self.instance:
if (
Document.objects.filter(title__iexact=title, org=self.org)
.exclude(id=self.instance.id)
.exists()
):
raise serializers.ValidationError(
"Document with this Title already exists"
)
else:
if Document.objects.filter(title__iexact=title, org=self.org).exists():
raise serializers.ValidationError("Document with this Title already exists")
return title
class Meta:
model = Document
fields = ["title", "document_file", "status", "org"]
read_only_fields = ["org"]
def find_urls(string):
# website_regex = "^((http|https)://)?([A-Za-z0-9.-]+\.[A-Za-z]{2,63})?$" # (http(s)://)google.com or google.com
# website_regex = "^https?://([A-Za-z0-9.-]+\.[A-Za-z]{2,63})?$" # (http(s)://)google.com
# http(s)://google.com
website_regex = r"^https?://[A-Za-z0-9.-]+\.[A-Za-z]{2,63}$"
# http(s)://google.com:8000
website_regex_port = r"^https?://[A-Za-z0-9.-]+\.[A-Za-z]{2,63}:[0-9]{2,4}$"
url = re.findall(website_regex, string)
url_port = re.findall(website_regex_port, string)
if url and url[0] != "":
return url
return url_port
class APISettingsSerializer(serializers.ModelSerializer):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
class Meta:
model = APISettings
fields = ("title", "website")
def validate_website(self, website):
if website and not (
website.startswith("http://") or website.startswith("https://")
):
raise serializers.ValidationError("Please provide valid schema")
if not len(find_urls(website)) > 0:
raise serializers.ValidationError(
"Please provide a valid URL with schema and without trailing slash - Example: http://google.com"
)
return website
class APISettingsListSerializer(serializers.ModelSerializer):
created_by = UserSerializer()
lead_assigned_to = ProfileSerializer(read_only=True, many=True)
tags = serializers.SerializerMethodField()
org = OrganizationSerializer()
@extend_schema_field(list)
def get_tags(self, obj):
return obj.tags.all().values()
class Meta:
model = APISettings
fields = [
"title",
"apikey",
"website",
"created_at",
"created_by",
"lead_assigned_to",
"tags",
"org",
]
class APISettingsSwaggerSerializer(serializers.ModelSerializer):
class Meta:
model = APISettings
fields = [
"title",
"website",
"lead_assigned_to",
"tags",
]
class DocumentCreateSwaggerSerializer(serializers.ModelSerializer):
class Meta:
model = Document
fields = [
"title",
"document_file",
"teams",
"shared_to",
]
class DocumentEditSwaggerSerializer(serializers.ModelSerializer):
class Meta:
model = Document
fields = ["title", "document_file", "teams", "shared_to", "status"]
class UserCreateSwaggerSerializer(serializers.Serializer):
"""
It is swagger for creating or updating user
"""
ROLE_CHOICES = ["ADMIN", "USER"]
email = serializers.CharField(max_length=1000, required=True)
role = serializers.ChoiceField(choices=ROLE_CHOICES, required=True)
phone = serializers.CharField(max_length=12)
alternate_phone = serializers.CharField(max_length=12)
address_line = serializers.CharField(max_length=10000, required=True)
street = serializers.CharField(max_length=1000)
city = serializers.CharField(max_length=1000)
state = serializers.CharField(max_length=1000)
pincode = serializers.CharField(max_length=1000)
country = serializers.CharField(max_length=1000)
class UserUpdateStatusSwaggerSerializer(serializers.Serializer):
STATUS_CHOICES = ["Active", "Inactive"]
status = serializers.ChoiceField(choices=STATUS_CHOICES, required=True)
# JWT Authentication Serializers for SvelteKit Integration
class MagicLinkRequestSerializer(serializers.Serializer):
"""Serializer for requesting a magic link."""
email = serializers.EmailField(required=True)
def validate_email(self, value):
domain = value.rsplit("@", 1)[-1].lower()
if domain in disposable_domains:
raise serializers.ValidationError(
"Disposable email addresses are not allowed."
)
return value
class MagicLinkVerifySerializer(serializers.Serializer):
"""Serializer for verifying a magic link token."""
token = serializers.CharField(required=True, max_length=64)
class UserDetailSerializer(serializers.ModelSerializer):
"""Detailed user serializer with profile and organizations"""
organizations = serializers.SerializerMethodField()
class Meta:
model = User
fields = ["id", "email", "profile_pic", "is_active", "organizations"]
@extend_schema_field(list)
def get_organizations(self, obj):
"""Get all organizations the user belongs to"""
profiles = Profile.objects.filter(user=obj, is_active=True)
return [
{
"id": str(profile.org.id),
"name": profile.org.name,
"role": profile.role,
"is_organization_admin": profile.is_organization_admin,
"has_sales_access": profile.has_sales_access,
"has_marketing_access": profile.has_marketing_access,
}
for profile in profiles
]
class ProfileDetailSerializer(serializers.ModelSerializer):
"""Detailed profile serializer for authenticated user"""
user = UserSerializer(read_only=True)
org = OrganizationSerializer(read_only=True)
class Meta:
model = Profile
fields = [
"id",
"user",
"org",
"role",
"is_organization_admin",
"has_sales_access",
"has_marketing_access",
"phone",
"date_of_joining",
"is_active",
]
# Activity Serializers for Dashboard Recent Activities
class ActivityUserSerializer(serializers.Serializer):
"""Simplified user info for activity display"""
id = serializers.UUIDField(source="user.id")
email = serializers.EmailField(source="user.email")
name = serializers.SerializerMethodField()
profile_pic = serializers.CharField(source="user.profile_pic", allow_null=True)
@extend_schema_field(str)
def get_name(self, obj):
"""Get display name from email"""
return obj.user.email.split("@")[0]
class ActivitySerializer(serializers.ModelSerializer):
"""Serializer for recent activities"""
user = ActivityUserSerializer(read_only=True)
action_display = serializers.CharField(source="get_action_display", read_only=True)
timestamp = serializers.DateTimeField(source="created_at", read_only=True)
humanized_time = serializers.CharField(source="created_on_arrow", read_only=True)
class Meta:
model = Activity
fields = [
"id",
"user",
"action",
"action_display",
"entity_type",
"entity_id",
"entity_name",
"description",
"timestamp",
"humanized_time",
]
class TeamsSerializer(serializers.ModelSerializer):
users = ProfileSerializer(read_only=True, many=True)
created_by = UserSerializer()
class Meta:
model = Teams
fields = (
"id",
"name",
"description",
"users",
"created_at",
"created_by",
)
class TeamCreateSerializer(serializers.ModelSerializer):
def __init__(self, *args, **kwargs):
request_obj = kwargs.pop("request_obj", None)
super().__init__(*args, **kwargs)
self.org = request_obj.profile.org
self.fields["name"].required = True
self.fields["description"].required = False
def validate_name(self, name):
if self.instance:
if (
Teams.objects.filter(name__iexact=name, org=self.org)
.exclude(id=self.instance.id)
.exists()
):
raise serializers.ValidationError("Team already exists with this name")
else:
if Teams.objects.filter(name__iexact=name, org=self.org).exists():
raise serializers.ValidationError("Team already exists with this name")
return name
class Meta:
model = Teams
fields = (
"name",
"description",
"created_at",
"created_by",
"org",
)
read_only_fields = ("created_at", "created_by", "org")
class TeamswaggerCreateSerializer(serializers.ModelSerializer):
class Meta:
model = Teams
fields = (
"name",
"description",
"users",
)