-
Notifications
You must be signed in to change notification settings - Fork 81
/
serializers.py
314 lines (244 loc) · 10.2 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
from django.conf import settings
from django.db.models import Q
from django.core.mail import send_mail
from django.core.urlresolvers import reverse
from core.util import slugify
from django.utils.translation import ugettext as _
from django.template.loader import get_template
from django.template import Context
from rest_framework import serializers
from rest_framework_gis import serializers as geo_serializers
from django_countries.serializer_fields import CountryField
from core.serializers import DetailSerializer, FieldSelectorSerializer
from accounts.models import User
from accounts.serializers import UserSerializer
from .models import Organization, Project, OrganizationRole, ProjectRole
class OrganizationSerializer(DetailSerializer, FieldSelectorSerializer,
serializers.ModelSerializer):
users = UserSerializer(many=True, read_only=True)
class Meta:
model = Organization
fields = ('id', 'slug', 'name', 'description', 'archived', 'urls',
'contacts', 'users',)
read_only_fields = ('id', 'slug',)
detail_only_fields = ('users',)
def validate_name(self, value):
invalid_names = settings.CADASTA_INVALID_ENTITY_NAMES
if slugify(value, allow_unicode=True) in invalid_names:
raise serializers.ValidationError(
_("Organization name cannot be “Add” or “New”."))
return value
def create(self, *args, **kwargs):
org = super(OrganizationSerializer, self).create(*args, **kwargs)
OrganizationRole.objects.create(
organization=org,
user=self.context['request'].user,
admin=True
)
return org
def update(self, *args, **kwargs):
org = super(OrganizationSerializer, self).update(*args, **kwargs)
data = args[1]
if 'archived' in data.keys():
for project in org.projects.all():
project.archived = data['archived']
project.save()
return org
class ProjectSerializer(DetailSerializer, serializers.ModelSerializer):
users = UserSerializer(many=True, read_only=True)
organization = OrganizationSerializer(hide_detail=True, read_only=True)
country = CountryField(required=False)
def validate_name(self, value):
# Check that name is not restricted
invalid_names = settings.CADASTA_INVALID_ENTITY_NAMES
if slugify(value, allow_unicode=True) in invalid_names:
raise serializers.ValidationError(
_("Project name cannot be “Add” or “New”."))
# Check that name is unique org-wide
# (Explicit validation: see comment in the Meta class)
is_create = not self.instance
if is_create:
org_slug = self.context['organization'].slug
else:
org_slug = self.instance.organization.slug
queryset = Project.objects.filter(
organization__slug=org_slug,
name=value,
)
if is_create:
not_unique = queryset.exists()
else:
not_unique = queryset.exclude(id=self.instance.id).exists()
if not_unique:
raise serializers.ValidationError(
_("Project with this name already exists "
"in this organization."))
return value
class Meta:
model = Project
fields = ('id', 'organization', 'country', 'name', 'description',
'archived', 'urls', 'contacts', 'users', 'access', 'slug')
read_only_fields = ('id', 'country', 'slug')
detail_only_fields = ('users',)
# Suppress automatic model-derived UniqueTogetherValidator because
# organization is a read-only field in the serializer.
# Instead, perform this validation explicitly in validate_name()
validators = []
def create(self, validated_data):
organization = self.context['organization']
return Project.objects.create(
organization_id=organization.id,
**validated_data
)
class NestedProjectSerializer(DetailSerializer, FieldSelectorSerializer,
serializers.ModelSerializer):
organization = OrganizationSerializer(
read_only=True, fields=('id', 'name', 'slug')
)
class Meta:
model = Project
fields = ('id', 'organization', 'name', 'slug')
read_only_fields = ('id', 'slug')
detail_only_fields = ('organization',)
class ProjectGeometrySerializer(geo_serializers.GeoFeatureModelSerializer):
org = serializers.SerializerMethodField()
url = serializers.SerializerMethodField()
class Meta:
model = Project
geo_field = 'extent'
fields = ('name', 'org', 'url')
def get_org(self, object):
return object.organization.name
def get_url(self, object):
return reverse(
'organization:project-dashboard',
kwargs={'organization': object.organization.slug,
'project': object.slug})
class EntityUserSerializer(serializers.Serializer):
username = serializers.CharField()
def to_representation(self, instance):
if isinstance(instance, User):
rep = UserSerializer(instance).data
rep[self.Meta.role_key] = self.get_role_json(instance)
return rep
def to_internal_value(self, data):
data[self.Meta.role_key] = self.set_roles(
data.get(self.Meta.role_key, None)
)
return super().to_internal_value(data)
def validate_username(self, value):
error = ""
if not self.instance:
users = User.objects.filter(Q(username=value) | Q(email=value))
users_count = len(users)
if users_count == 0:
error = _("User with username or email {} does not exist")
elif users_count > 1:
error = _("More than one user found for username or email {}")
else:
self.user = users[0]
if error:
raise serializers.ValidationError(error.format(value))
def validate_admin(self, role_value):
if 'request' in self.context:
if self.context['request'].user == self.instance:
if role_value != self.get_roles_object(self.instance).admin:
raise serializers.ValidationError(
_("Organization administrators cannot change their "
"own permissions within the organization"))
return role_value
def create(self, validated_data):
obj = self.context[self.Meta.context_key]
role_value = validated_data[self.Meta.role_key]
create_kwargs = {
self.Meta.role_key: role_value,
self.Meta.context_key: obj,
'user': self.user,
}
self.role = self.Meta.role_model.objects.create(**create_kwargs)
if hasattr(self, 'send_invitaion_email'):
self.send_invitaion_email()
return self.user
def update(self, instance, validated_data):
role = self.get_roles_object(instance)
role_value = validated_data[self.Meta.role_key]
if self.Meta.role_key in validated_data:
setattr(role, self.Meta.role_key, role_value)
role.save()
return instance
class OrganizationUserSerializer(EntityUserSerializer):
class Meta:
role_model = OrganizationRole
context_key = 'organization'
role_key = 'admin'
admin = serializers.BooleanField()
def get_roles_object(self, instance):
self.role = OrganizationRole.objects.get(
user=instance,
organization=self.context['organization'])
return self.role
def get_role_json(self, instance):
role = self.get_roles_object(instance)
return role.admin
def set_roles(self, data):
admin = False
if self.instance:
role = self.get_roles_object(self.instance)
admin = role.admin
if data:
admin = data
return admin
def send_invitaion_email(self):
template = get_template('organization/email/org_invite.txt')
organization = self.context['organization']
context = Context({
'site_name': self.context['sitename'],
'organization': organization.name,
'domain': self.context['domain'],
'url': 'organizations/{}/leave'.format(organization.slug),
})
message = template.render(context)
print(message)
subject = _(
"You have been added to organization {organization}"
).format(
organization=self.context['organization'].name
)
from_email = getattr(settings, 'DEFAULT_FROM_EMAIL', None),
send_mail(subject, message, from_email, [self.user.email])
class ProjectUserSerializer(EntityUserSerializer):
class Meta:
role_model = ProjectRole
context_key = 'project'
role_key = 'role'
role = serializers.CharField()
def validate_username(self, value):
super(ProjectUserSerializer, self).validate_username(value)
project = self.context[self.Meta.context_key]
if self.user not in project.organization.users.all():
raise serializers.ValidationError(
_("User {username} is not member of the project\'s "
"organization").format(username=value))
def get_roles_object(self, instance):
self.role = ProjectRole.objects.get(
user=instance,
project=self.context['project'])
return self.role
def get_role_json(self, instance):
role = self.get_roles_object(instance)
return role.role
def set_roles(self, data):
user_role = 'PU'
if self.instance:
role = self.get_roles_object(self.instance)
user_role = role.role
if data:
user_role = data
return user_role
class UserAdminSerializer(UserSerializer):
organizations = OrganizationSerializer(
many=True, read_only=True, fields=('id', 'name'))
class Meta:
model = User
fields = ('username', 'full_name', 'email',
'organizations', 'last_login', 'is_active')