-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
serializers.py
3033 lines (2541 loc) · 106 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
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
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import json
import logging
import os
import re
from datetime import datetime
import six
import tagulous
from django.conf import settings
from django.contrib.auth.models import Group, Permission
from django.contrib.auth.password_validation import validate_password
from django.core.exceptions import PermissionDenied, ValidationError
from django.db.utils import IntegrityError
from django.urls import reverse
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
from drf_spectacular.utils import extend_schema_field
from rest_framework import serializers
from rest_framework.exceptions import NotFound
from rest_framework.exceptions import ValidationError as RestFrameworkValidationError
from rest_framework.fields import DictField, MultipleChoiceField
import dojo.jira_link.helper as jira_helper
from dojo.authorization.authorization import user_has_permission
from dojo.authorization.roles_permissions import Permissions
from dojo.endpoint.utils import endpoint_filter, endpoint_meta_import
from dojo.finding.helper import (
save_vulnerability_ids,
save_vulnerability_ids_template,
)
from dojo.finding.queries import get_authorized_findings
from dojo.group.utils import get_auth_group_name
from dojo.importers.auto_create_context import AutoCreateContextManager
from dojo.importers.base_importer import BaseImporter
from dojo.importers.default_importer import DefaultImporter
from dojo.importers.default_reimporter import DefaultReImporter
from dojo.models import (
DEFAULT_NOTIFICATION,
IMPORT_ACTIONS,
NOTIFICATION_CHOICES,
SEVERITIES,
SEVERITY_CHOICES,
STATS_FIELDS,
Announcement,
Answer,
Answered_Survey,
App_Analysis,
Check_List,
ChoiceAnswer,
ChoiceQuestion,
Cred_Mapping,
Cred_User,
Development_Environment,
Dojo_Group,
Dojo_Group_Member,
Dojo_User,
DojoMeta,
Endpoint,
Endpoint_Params,
Endpoint_Status,
Engagement,
Engagement_Presets,
Engagement_Survey,
FileUpload,
Finding,
Finding_Group,
Finding_Template,
General_Survey,
Global_Role,
JIRA_Instance,
JIRA_Issue,
JIRA_Project,
Language_Type,
Languages,
Network_Locations,
Note_Type,
NoteHistory,
Notes,
Notification_Webhooks,
Notifications,
Product,
Product_API_Scan_Configuration,
Product_Group,
Product_Member,
Product_Type,
Product_Type_Group,
Product_Type_Member,
Question,
Regulation,
Risk_Acceptance,
Role,
SLA_Configuration,
Sonarqube_Issue,
Sonarqube_Issue_Transition,
Stub_Finding,
System_Settings,
Test,
Test_Import,
Test_Import_Finding_Action,
Test_Type,
TextAnswer,
TextQuestion,
Tool_Configuration,
Tool_Product_Settings,
Tool_Type,
User,
UserContactInfo,
Vulnerability_Id,
Vulnerability_Id_Template,
get_current_date,
)
from dojo.risk_acceptance.helper import add_findings_to_risk_acceptance, remove_finding_from_risk_acceptance
from dojo.tools.factory import (
get_choices_sorted,
requires_file,
requires_tool_type,
)
from dojo.user.utils import get_configuration_permissions_codenames
from dojo.utils import is_scan_file_too_large
logger = logging.getLogger(__name__)
deduplicationLogger = logging.getLogger("dojo.specific-loggers.deduplication")
def get_product_id_from_dict(data):
product_id = data.get("product", None)
if product_id:
if isinstance(product_id, Product):
product_id = product_id.id
elif isinstance(product_id, str) and not product_id.isdigit():
msg = "product must be an integer"
raise serializers.ValidationError(msg)
return product_id
class StatusStatisticsSerializer(serializers.Serializer):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for stat in STATS_FIELDS:
self.fields[stat.lower()] = serializers.IntegerField()
class SeverityStatusStatisticsSerializer(serializers.Serializer):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for sev in SEVERITIES:
self.fields[sev.lower()] = StatusStatisticsSerializer()
self.fields["total"] = StatusStatisticsSerializer()
class DeltaStatisticsSerializer(serializers.Serializer):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for action in IMPORT_ACTIONS:
self.fields[
action[1].lower()
] = SeverityStatusStatisticsSerializer()
class ImportStatisticsSerializer(serializers.Serializer):
before = SeverityStatusStatisticsSerializer(
required=False,
help_text="Finding statistics as stored in Defect Dojo before the import",
)
delta = DeltaStatisticsSerializer(
required=False,
help_text="Finding statistics of modifications made by the reimport. Only available when TRACK_IMPORT_HISTORY hass not disabled.",
)
after = SeverityStatusStatisticsSerializer(
help_text="Finding statistics as stored in Defect Dojo after the import",
)
@extend_schema_field(
serializers.ListField(child=serializers.CharField()),
) # also takes basic python types
class TagListSerializerField(serializers.ListField):
child = serializers.CharField()
default_error_messages = {
"not_a_list": _(
'Expected a list of items but got type "{input_type}".',
),
"invalid_json": _(
"Invalid json list. A tag list submitted in string"
" form must be valid json.",
),
"not_a_str": _("All list items must be of string type."),
}
order_by = None
def __init__(self, **kwargs):
pretty_print = kwargs.pop("pretty_print", True)
style = kwargs.pop("style", {})
kwargs["style"] = {"base_template": "textarea.html"}
kwargs["style"].update(style)
super().__init__(**kwargs)
self.pretty_print = pretty_print
def to_internal_value(self, data):
if isinstance(data, list) and data == [""] and self.allow_empty:
return []
if isinstance(data, six.string_types):
if not data:
data = []
try:
data = json.loads(data)
except ValueError:
self.fail("invalid_json")
logger.debug(f"data as json: {data}")
if not isinstance(data, list):
self.fail("not_a_list", input_type=type(data).__name__)
data_safe = []
for s in data:
# Ensure if the element in the list is string
if not isinstance(s, six.string_types):
self.fail("not_a_str")
# Run the children validation
self.child.run_validation(s)
substrings = re.findall(r'(?:"[^"]*"|[^",]+)', s)
data_safe.extend(substrings)
return tagulous.utils.render_tags(data_safe)
def to_representation(self, value):
if not isinstance(value, list):
# we can't use isinstance because TagRelatedManager is non-existing class
# it cannot be imported or referenced, so we fallback to string
# comparison
if type(value).__name__ == "TagRelatedManager":
value = value.get_tag_list()
elif isinstance(value, str):
value = tagulous.utils.parse_tags(value)
else:
msg = f"unable to convert {type(value).__name__} into list of tags"
raise ValueError(msg)
return value
class TaggitSerializer(serializers.Serializer):
def create(self, validated_data):
to_be_tagged, validated_data = self._pop_tags(validated_data)
tag_object = super().create(validated_data)
return self._save_tags(tag_object, to_be_tagged)
def update(self, instance, validated_data):
to_be_tagged, validated_data = self._pop_tags(validated_data)
tag_object = super().update(
instance, validated_data,
)
return self._save_tags(tag_object, to_be_tagged)
def _save_tags(self, tag_object, tags):
for key in list(tags.keys()):
tag_values = tags.get(key)
# tag_object.tags = ", ".join(tag_values)
tag_object.tags = tag_values
tag_object.save()
return tag_object
def _pop_tags(self, validated_data):
to_be_tagged = {}
for key in list(self.fields.keys()):
field = self.fields[key]
if isinstance(field, TagListSerializerField):
if key in validated_data:
to_be_tagged[key] = validated_data.pop(key)
return (to_be_tagged, validated_data)
class RequestResponseDict(list):
def __init__(self, *args, **kwargs):
pretty_print = kwargs.pop("pretty_print", True)
list.__init__(self, *args, **kwargs)
self.pretty_print = pretty_print
def __add__(self, rhs):
return RequestResponseDict(list.__add__(self, rhs))
def __getitem__(self, item):
result = list.__getitem__(self, item)
try:
return RequestResponseDict(result)
except TypeError:
return result
def __str__(self):
if self.pretty_print:
return json.dumps(
self, sort_keys=True, indent=4, separators=(",", ": "),
)
return json.dumps(self)
class RequestResponseSerializerField(serializers.ListSerializer):
child = DictField(child=serializers.CharField())
default_error_messages = {
"not_a_list": _(
'Expected a list of items but got type "{input_type}".',
),
"invalid_json": _(
"Invalid json list. A tag list submitted in string"
" form must be valid json.",
),
"not_a_dict": _(
"All list items must be of dict type with keys 'request' and 'response'",
),
"not_a_str": _("All values in the dict must be of string type."),
}
order_by = None
def __init__(self, **kwargs):
pretty_print = kwargs.pop("pretty_print", True)
style = kwargs.pop("style", {})
kwargs["style"] = {"base_template": "textarea.html"}
kwargs["style"].update(style)
if "data" in kwargs:
data = kwargs["data"]
if isinstance(data, list):
kwargs["many"] = True
super().__init__(**kwargs)
self.pretty_print = pretty_print
def to_internal_value(self, data):
if isinstance(data, six.string_types):
if not data:
data = []
try:
data = json.loads(data)
except ValueError:
self.fail("invalid_json")
if not isinstance(data, list):
self.fail("not_a_list", input_type=type(data).__name__)
for s in data:
if not isinstance(s, dict):
self.fail("not_a_dict", input_type=type(s).__name__)
request = s.get("request", None)
response = s.get("response", None)
if not isinstance(request, str):
self.fail("not_a_str", input_type=type(request).__name__)
if not isinstance(response, str):
self.fail("not_a_str", input_type=type(request).__name__)
self.child.run_validation(s)
return data
def to_representation(self, value):
if not isinstance(value, RequestResponseDict):
if not isinstance(value, list):
# this will trigger when a queryset is found...
if self.order_by:
burps = value.all().order_by(*self.order_by)
else:
burps = value.all()
value = [
{
"request": burp.get_request(),
"response": burp.get_response(),
}
for burp in burps
]
return value
class BurpRawRequestResponseSerializer(serializers.Serializer):
req_resp = RequestResponseSerializerField(required=True)
class MetaSerializer(serializers.ModelSerializer):
product = serializers.PrimaryKeyRelatedField(
queryset=Product.objects.all(),
required=False,
default=None,
allow_null=True,
)
endpoint = serializers.PrimaryKeyRelatedField(
queryset=Endpoint.objects.all(),
required=False,
default=None,
allow_null=True,
)
finding = serializers.PrimaryKeyRelatedField(
queryset=Finding.objects.all(),
required=False,
default=None,
allow_null=True,
)
def validate(self, data):
DojoMeta(**data).clean()
return data
class Meta:
model = DojoMeta
fields = "__all__"
class ProductMetaSerializer(serializers.ModelSerializer):
class Meta:
model = DojoMeta
fields = ("name", "value")
class UserSerializer(serializers.ModelSerializer):
date_joined = serializers.DateTimeField(read_only=True)
last_login = serializers.DateTimeField(read_only=True, allow_null=True)
email = serializers.EmailField(required=True)
password = serializers.CharField(
write_only=True,
style={"input_type": "password"},
required=False,
validators=[validate_password],
)
configuration_permissions = serializers.PrimaryKeyRelatedField(
allow_null=True,
queryset=Permission.objects.filter(
codename__in=get_configuration_permissions_codenames(),
),
many=True,
required=False,
source="user_permissions",
)
class Meta:
model = Dojo_User
fields = (
"id",
"username",
"first_name",
"last_name",
"email",
"date_joined",
"last_login",
"is_active",
"is_superuser",
"password",
"configuration_permissions",
)
def to_representation(self, instance):
ret = super().to_representation(instance)
# This will show only "configuration_permissions" even if user has also
# other permissions
all_permissions = set(ret["configuration_permissions"])
allowed_configuration_permissions = set(
self.fields[
"configuration_permissions"
].child_relation.queryset.values_list("id", flat=True),
)
ret["configuration_permissions"] = list(
all_permissions.intersection(allowed_configuration_permissions),
)
return ret
def update(self, instance, validated_data):
new_configuration_permissions = None
if (
"user_permissions" in validated_data
): # This field was renamed from "configuration_permissions" in the meantime
new_configuration_permissions = set(
validated_data.pop("user_permissions"),
)
instance = super().update(instance, validated_data)
# This will update only Permissions from category
# "configuration_permissions". Others will be untouched
if new_configuration_permissions:
allowed_configuration_permissions = set(
self.fields[
"configuration_permissions"
].child_relation.queryset.all(),
)
non_configuration_permissions = (
set(instance.user_permissions.all())
- allowed_configuration_permissions
)
new_permissions = non_configuration_permissions.union(
new_configuration_permissions,
)
instance.user_permissions.set(new_permissions)
return instance
def create(self, validated_data):
if "password" in validated_data:
password = validated_data.pop("password")
else:
password = None
new_configuration_permissions = None
if (
"user_permissions" in validated_data
): # This field was renamed from "configuration_permissions" in the meantime
new_configuration_permissions = set(
validated_data.pop("user_permissions"),
)
user = Dojo_User.objects.create(**validated_data)
if password:
user.set_password(password)
else:
user.set_unusable_password()
# This will create only Permissions from category
# "configuration_permissions". There are no other Permissions.
if new_configuration_permissions:
user.user_permissions.set(new_configuration_permissions)
user.save()
return user
def validate(self, data):
if self.instance is not None:
instance_is_superuser = self.instance.is_superuser
else:
instance_is_superuser = False
data_is_superuser = data.get("is_superuser", False)
if not self.context["request"].user.is_superuser and (
instance_is_superuser or data_is_superuser
):
msg = "Only superusers are allowed to add or edit superusers."
raise ValidationError(msg)
if self.context["request"].method in ["PATCH", "PUT"] and "password" in data:
msg = "Update of password though API is not allowed"
raise ValidationError(msg)
if self.context["request"].method == "POST" and "password" not in data and settings.REQUIRE_PASSWORD_ON_USER:
msg = "Passwords must be supplied for new users"
raise ValidationError(msg)
return super().validate(data)
class UserContactInfoSerializer(serializers.ModelSerializer):
user_profile = UserSerializer(many=False, source="user", read_only=True)
class Meta:
model = UserContactInfo
fields = "__all__"
class UserStubSerializer(serializers.ModelSerializer):
class Meta:
model = Dojo_User
fields = ("id", "username", "first_name", "last_name")
class RoleSerializer(serializers.ModelSerializer):
class Meta:
model = Role
fields = "__all__"
class DojoGroupSerializer(serializers.ModelSerializer):
configuration_permissions = serializers.PrimaryKeyRelatedField(
allow_null=True,
queryset=Permission.objects.filter(
codename__in=get_configuration_permissions_codenames(),
),
many=True,
required=False,
source="auth_group.permissions",
)
class Meta:
model = Dojo_Group
exclude = ("auth_group",)
def to_representation(self, instance):
if not instance.auth_group:
auth_group = Group(name=get_auth_group_name(instance))
auth_group.save()
instance.auth_group = auth_group
members = instance.users.all()
for member in members:
auth_group.user_set.add(member)
instance.save()
ret = super().to_representation(instance)
# This will show only "configuration_permissions" even if user has also
# other permissions
all_permissions = set(ret["configuration_permissions"])
allowed_configuration_permissions = set(
self.fields[
"configuration_permissions"
].child_relation.queryset.values_list("id", flat=True),
)
ret["configuration_permissions"] = list(
all_permissions.intersection(allowed_configuration_permissions),
)
return ret
def create(self, validated_data):
new_configuration_permissions = None
if (
"auth_group" in validated_data
and "permissions" in validated_data["auth_group"]
): # This field was renamed from "configuration_permissions" in the meantime
new_configuration_permissions = set(
validated_data.pop("auth_group")["permissions"],
)
instance = super().create(validated_data)
# This will update only Permissions from category
# "configuration_permissions". There are no other Permissions.
if new_configuration_permissions:
instance.auth_group.permissions.set(new_configuration_permissions)
return instance
def update(self, instance, validated_data):
new_configuration_permissions = None
if (
"auth_group" in validated_data
and "permissions" in validated_data["auth_group"]
): # This field was renamed from "configuration_permissions" in the meantime
new_configuration_permissions = set(
validated_data.pop("auth_group")["permissions"],
)
instance = super().update(instance, validated_data)
# This will update only Permissions from category
# "configuration_permissions". Others will be untouched
if new_configuration_permissions:
allowed_configuration_permissions = set(
self.fields[
"configuration_permissions"
].child_relation.queryset.all(),
)
non_configuration_permissions = (
set(instance.auth_group.permissions.all())
- allowed_configuration_permissions
)
new_permissions = non_configuration_permissions.union(
new_configuration_permissions,
)
instance.auth_group.permissions.set(new_permissions)
return instance
class DojoGroupMemberSerializer(serializers.ModelSerializer):
class Meta:
model = Dojo_Group_Member
fields = "__all__"
def validate(self, data):
if (
self.instance is not None
and data.get("group") != self.instance.group
and not user_has_permission(
self.context["request"].user,
data.get("group"),
Permissions.Group_Manage_Members,
)
):
msg = "You are not permitted to add a user to this group"
raise PermissionDenied(msg)
if (
self.instance is None
or data.get("group") != self.instance.group
or data.get("user") != self.instance.user
):
members = Dojo_Group_Member.objects.filter(
group=data.get("group"), user=data.get("user"),
)
if members.count() > 0:
msg = "Dojo_Group_Member already exists"
raise ValidationError(msg)
if self.instance is not None and not data.get("role").is_owner:
owners = (
Dojo_Group_Member.objects.filter(
group=data.get("group"), role__is_owner=True,
)
.exclude(id=self.instance.id)
.count()
)
if owners < 1:
msg = "There must be at least one owner"
raise ValidationError(msg)
if data.get("role").is_owner and not user_has_permission(
self.context["request"].user,
data.get("group"),
Permissions.Group_Add_Owner,
):
msg = "You are not permitted to add a user as Owner to this group"
raise PermissionDenied(msg)
return data
class GlobalRoleSerializer(serializers.ModelSerializer):
class Meta:
model = Global_Role
fields = "__all__"
def validate(self, data):
user = None
group = None
if self.instance is not None:
user = self.instance.user
group = self.instance.group
if "user" in data:
user = data.get("user")
if "group" in data:
group = data.get("group")
if user is None and group is None:
msg = "Global_Role must have either user or group"
raise ValidationError(msg)
if user is not None and group is not None:
msg = "Global_Role cannot have both user and group"
raise ValidationError(msg)
return data
class AddUserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ("id", "username")
class NoteTypeSerializer(serializers.ModelSerializer):
class Meta:
model = Note_Type
fields = "__all__"
class NoteHistorySerializer(serializers.ModelSerializer):
current_editor = UserStubSerializer(read_only=True)
note_type = NoteTypeSerializer(read_only=True, many=False)
class Meta:
model = NoteHistory
fields = "__all__"
class NoteSerializer(serializers.ModelSerializer):
author = UserStubSerializer(many=False, read_only=True)
editor = UserStubSerializer(read_only=True, many=False, allow_null=True)
history = NoteHistorySerializer(read_only=True, many=True)
note_type = NoteTypeSerializer(read_only=True, many=False)
def update(self, instance, validated_data):
instance.entry = validated_data.get("entry")
instance.edited = True
instance.editor = self.context["request"].user
instance.edit_time = timezone.now()
history = NoteHistory(
data=instance.entry,
time=instance.edit_time,
current_editor=instance.editor,
)
history.save()
instance.history.add(history)
instance.save()
return instance
class Meta:
model = Notes
fields = "__all__"
class FileSerializer(serializers.ModelSerializer):
file = serializers.FileField(required=True)
class Meta:
model = FileUpload
fields = "__all__"
def validate(self, data):
if file := data.get("file"):
ext = os.path.splitext(file.name)[1] # [0] returns path+filename
valid_extensions = settings.FILE_UPLOAD_TYPES
if ext.lower() not in valid_extensions:
if accepted_extensions := f"{', '.join(valid_extensions)}":
msg = (
"Unsupported extension. Supported extensions are as "
f"follows: {accepted_extensions}"
)
else:
msg = (
"File uploads are prohibited due to the list of acceptable "
"file extensions being empty"
)
raise ValidationError(msg)
return data
return None
class RawFileSerializer(serializers.ModelSerializer):
file = serializers.FileField(required=True)
class Meta:
model = FileUpload
fields = ["file"]
class RiskAcceptanceProofSerializer(serializers.ModelSerializer):
path = serializers.FileField(required=True)
class Meta:
model = Risk_Acceptance
fields = ["path"]
class ProductMemberSerializer(serializers.ModelSerializer):
class Meta:
model = Product_Member
fields = "__all__"
def validate(self, data):
if (
self.instance is not None
and data.get("product") != self.instance.product
and not user_has_permission(
self.context["request"].user,
data.get("product"),
Permissions.Product_Manage_Members,
)
):
msg = "You are not permitted to add a member to this product"
raise PermissionDenied(msg)
if (
self.instance is None
or data.get("product") != self.instance.product
or data.get("user") != self.instance.user
):
members = Product_Member.objects.filter(
product=data.get("product"), user=data.get("user"),
)
if members.count() > 0:
msg = "Product_Member already exists"
raise ValidationError(msg)
if data.get("role").is_owner and not user_has_permission(
self.context["request"].user,
data.get("product"),
Permissions.Product_Member_Add_Owner,
):
msg = "You are not permitted to add a member as Owner to this product"
raise PermissionDenied(msg)
return data
class ProductGroupSerializer(serializers.ModelSerializer):
class Meta:
model = Product_Group
fields = "__all__"
def validate(self, data):
if (
self.instance is not None
and data.get("product") != self.instance.product
and not user_has_permission(
self.context["request"].user,
data.get("product"),
Permissions.Product_Group_Add,
)
):
msg = "You are not permitted to add a group to this product"
raise PermissionDenied(msg)
if (
self.instance is None
or data.get("product") != self.instance.product
or data.get("group") != self.instance.group
):
members = Product_Group.objects.filter(
product=data.get("product"), group=data.get("group"),
)
if members.count() > 0:
msg = "Product_Group already exists"
raise ValidationError(msg)
if data.get("role").is_owner and not user_has_permission(
self.context["request"].user,
data.get("product"),
Permissions.Product_Group_Add_Owner,
):
msg = "You are not permitted to add a group as Owner to this product"
raise PermissionDenied(msg)
return data
class ProductTypeMemberSerializer(serializers.ModelSerializer):
class Meta:
model = Product_Type_Member
fields = "__all__"
def validate(self, data):
if (
self.instance is not None
and data.get("product_type") != self.instance.product_type
and not user_has_permission(
self.context["request"].user,
data.get("product_type"),
Permissions.Product_Type_Manage_Members,
)
):
msg = "You are not permitted to add a member to this product type"
raise PermissionDenied(msg)
if (
self.instance is None
or data.get("product_type") != self.instance.product_type
or data.get("user") != self.instance.user
):
members = Product_Type_Member.objects.filter(
product_type=data.get("product_type"), user=data.get("user"),
)
if members.count() > 0:
msg = "Product_Type_Member already exists"
raise ValidationError(msg)
if self.instance is not None and not data.get("role").is_owner:
owners = (
Product_Type_Member.objects.filter(
product_type=data.get("product_type"), role__is_owner=True,
)
.exclude(id=self.instance.id)
.count()
)
if owners < 1:
msg = "There must be at least one owner"
raise ValidationError(msg)
if data.get("role").is_owner and not user_has_permission(
self.context["request"].user,
data.get("product_type"),
Permissions.Product_Type_Member_Add_Owner,
):
msg = "You are not permitted to add a member as Owner to this product type"
raise PermissionDenied(msg)
return data
class ProductTypeGroupSerializer(serializers.ModelSerializer):
class Meta:
model = Product_Type_Group
fields = "__all__"
def validate(self, data):
if (
self.instance is not None
and data.get("product_type") != self.instance.product_type
and not user_has_permission(
self.context["request"].user,
data.get("product_type"),
Permissions.Product_Type_Group_Add,
)
):
msg = "You are not permitted to add a group to this product type"
raise PermissionDenied(msg)
if (
self.instance is None
or data.get("product_type") != self.instance.product_type
or data.get("group") != self.instance.group
):
members = Product_Type_Group.objects.filter(
product_type=data.get("product_type"), group=data.get("group"),
)