forked from openedx/openedx-authz
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserializers.py
More file actions
294 lines (211 loc) · 11 KB
/
serializers.py
File metadata and controls
294 lines (211 loc) · 11 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
"""Serializers for the Open edX AuthZ REST API."""
from django.contrib.auth import get_user_model
from rest_framework import serializers
from openedx_authz import api
from openedx_authz.api.data import UserAssignments
from openedx_authz.rest_api.data import SortField, SortOrder
from openedx_authz.rest_api.utils import get_generic_scope
from openedx_authz.rest_api.v1.fields import (
CaseSensitiveCommaSeparatedListField,
CommaSeparatedListField,
LowercaseCharField,
)
User = get_user_model()
class ScopeMixin(serializers.Serializer): # pylint: disable=abstract-method
"""Mixin providing scope field functionality."""
scope = serializers.CharField(max_length=255)
class RoleMixin(serializers.Serializer): # pylint: disable=abstract-method
"""Mixin providing role field functionality."""
role = serializers.CharField(max_length=255)
class ActionMixin(serializers.Serializer): # pylint: disable=abstract-method
"""Mixin providing action field functionality."""
action = serializers.CharField(max_length=255)
class PermissionValidationSerializer(ActionMixin, ScopeMixin): # pylint: disable=abstract-method
"""Serializer for permission validation request."""
class PermissionValidationResponseSerializer(PermissionValidationSerializer): # pylint: disable=abstract-method
"""Serializer for permission validation response."""
allowed = serializers.BooleanField()
class RoleScopeValidationMixin(serializers.Serializer): # pylint: disable=abstract-method
"""Mixin providing role and scope validation logic."""
def validate(self, attrs) -> dict:
"""Validate that the specified role and scope are valid and that the role exists in the scope.
This method performs the following validations:
1. Validates that the scope is registered in the scope registry
2. Validates that the scope exists in the system
3. Validates that the role is defined into the roles assigned to the scope
Args:
attrs: Dictionary containing 'role' and 'scope' keys with their string values.
Returns:
dict: The validated data dictionary with 'role' and 'scope' keys.
Raises:
serializers.ValidationError: If the scope is not registered, doesn't exist,
or if the role is not defined in the scope.
"""
validated_data = super().validate(attrs)
scope_value = validated_data["scope"]
role_value = validated_data["role"]
try:
scope = api.ScopeData(external_key=scope_value)
except ValueError as exc:
raise serializers.ValidationError({"scope": str(exc)}) from exc
if not scope.exists():
raise serializers.ValidationError({"scope": f"Scope '{scope_value}' does not exist"})
role = api.RoleData(external_key=role_value)
generic_scope = get_generic_scope(scope)
role_definitions = api.get_role_definitions_in_scope(generic_scope)
if role not in role_definitions:
raise serializers.ValidationError({"role": f"Role '{role_value}' does not exist in scope '{scope_value}'"})
return validated_data
class AddUsersToRoleWithScopeSerializer(
RoleScopeValidationMixin,
RoleMixin,
ScopeMixin,
): # pylint: disable=abstract-method
"""Serializer for adding users to a role with a scope."""
users = serializers.ListField(child=serializers.CharField(max_length=255), allow_empty=False)
def validate_users(self, value) -> list[str]:
"""Eliminate duplicates preserving order"""
return list(dict.fromkeys(value))
class RemoveUsersFromRoleWithScopeSerializer(
RoleScopeValidationMixin,
RoleMixin,
ScopeMixin,
): # pylint: disable=abstract-method
"""Serializer for removing users from a role with a scope."""
users = CommaSeparatedListField(allow_blank=False)
class ListUsersInRoleWithScopeSerializer(ScopeMixin): # pylint: disable=abstract-method
"""Serializer for listing users in a role with a scope."""
roles = CommaSeparatedListField(required=False, default=[])
sort_by = serializers.ChoiceField(
required=False,
choices=[(e.value, e.name) for e in SortField],
default=SortField.USERNAME,
)
order = serializers.ChoiceField(
required=False,
choices=[(e.value, e.name) for e in SortOrder],
default=SortOrder.ASC,
)
search = LowercaseCharField(required=False, default=None)
class ListRolesWithScopeSerializer(serializers.Serializer): # pylint: disable=abstract-method
"""Serializer for listing roles within a scope."""
scope = serializers.CharField(max_length=255)
def validate_scope(self, value: str) -> api.ScopeData:
"""Validate and convert scope string to a ScopeData instance.
Checks that the provided scope is registered in the scope registry and
returns an instance of the appropriate ScopeData subclass.
Args:
value: The scope string to validate (e.g., 'lib', 'global', 'org').
Returns:
ScopeData: An instance of the appropriate ScopeData subclass for the scope.
Raises:
serializers.ValidationError: If the scope is not registered in the scope registry.
Examples:
>>> validate_scope('lib:DemoX:CSPROB')
ContentLibraryData(external_key='lib:DemoX:CSPROB')
"""
try:
return api.ScopeData(external_key=value)
except ValueError as exc:
raise serializers.ValidationError(exc) from exc
class ListUsersInRoleWithScopeResponseSerializer(serializers.Serializer): # pylint: disable=abstract-method
"""Serializer for listing users in a role with a scope response."""
username = serializers.CharField(max_length=255)
full_name = serializers.CharField(max_length=255)
email = serializers.EmailField()
class ListRolesWithScopeResponseSerializer(serializers.Serializer): # pylint: disable=abstract-method
"""Serializer for listing roles with a scope response."""
role = serializers.CharField(max_length=255)
permissions = serializers.ListField(child=serializers.CharField(max_length=255))
user_count = serializers.IntegerField()
class UserRoleAssignmentSerializer(serializers.Serializer): # pylint: disable=abstract-method
"""Serializer for a user role assignment."""
username = serializers.SerializerMethodField()
full_name = serializers.SerializerMethodField()
email = serializers.SerializerMethodField()
roles = serializers.SerializerMethodField()
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._user_cache = {}
def _get_user(self, obj) -> User | None:
"""Get the user object for the given role assignment."""
user_map = self.context.get("user_map", {})
return user_map.get(obj.subject.username)
def get_username(self, obj: api.RoleAssignmentData) -> str:
"""Get the username for the given role assignment."""
return obj.subject.username
def get_full_name(self, obj) -> str:
"""Get the full name for the given role assignment."""
user = self._get_user(obj)
return getattr(user.profile, "name", "") if user and hasattr(user, "profile") else ""
def get_email(self, obj) -> str:
"""Get the email for the given role assignment."""
user = self._get_user(obj)
return getattr(user, "email", "") if user else ""
def get_roles(self, obj: api.RoleAssignmentData) -> list[str]:
"""Get the roles for the given role assignment."""
return [role.external_key for role in obj.roles]
class ListTeamMembersSerializer(serializers.Serializer): # pylint: disable=abstract-method
"""
Serializer for listing team members.
This serializer is TeamMembersAPIView, which is used in the Admin Console.
In this content, a team member is anyone with studio access.
"""
scopes = CaseSensitiveCommaSeparatedListField(required=False, default=[])
orgs = CaseSensitiveCommaSeparatedListField(required=False, default=[])
sort_by = serializers.ChoiceField(
required=False,
choices=[(e.value, e.name) for e in SortField],
default=SortField.USERNAME,
)
order = serializers.ChoiceField(
required=False,
choices=[(e.value, e.name) for e in SortOrder],
default=SortOrder.ASC,
)
search = LowercaseCharField(required=False, default=None)
class TeamMemberSerializer(serializers.Serializer): # pylint: disable=abstract-method
"""
Serializer for team members.
This serializer is APIs used by the Admin Console.
In this content, a team member is anyone with studio access.
"""
username = serializers.SerializerMethodField()
full_name = serializers.SerializerMethodField()
email = serializers.SerializerMethodField()
assignation_count = serializers.SerializerMethodField()
def get_username(self, obj: UserAssignments) -> str:
"""Get the username for the given role assignment."""
return getattr(obj.user, "username", "") if obj.user else ""
def get_full_name(self, obj: UserAssignments) -> str:
"""Get the full name for the given role assignment."""
return obj.user.get_full_name() if obj.user else ""
def get_email(self, obj: UserAssignments) -> str:
"""Get the email for the given role assignment."""
return getattr(obj.user, "email", "") if obj.user else ""
def get_assignation_count(self, obj: UserAssignments) -> int:
"""Get the assignation count for the given role assignment."""
return len(obj.assignments)
class UserValidationAPIViewSerializer(serializers.Serializer): # pylint: disable=abstract-method
"""Serializer for validating user existence."""
users = serializers.ListField(
child=serializers.CharField(max_length=255), allow_empty=False, help_text="List of user identifiers to validate"
)
def validate_users(self, value) -> list[str]:
"""Eliminate duplicates preserving order"""
return list(dict.fromkeys(value))
class UserValidationSummarySerializer(serializers.Serializer): # pylint: disable=abstract-method
"""Serializer for user validation summary statistics."""
total = serializers.IntegerField(help_text="Total number of users validated")
valid_count = serializers.IntegerField(help_text="Number of valid users found")
invalid_count = serializers.IntegerField(help_text="Number of invalid users")
class UserValidationAPIViewResponseSerializer(serializers.Serializer): # pylint: disable=abstract-method
"""Serializer for user validation response."""
valid_users = serializers.ListField(
child=serializers.CharField(max_length=255), help_text="List of user identifiers that were found to be valid"
)
invalid_users = serializers.ListField(
child=serializers.CharField(max_length=255),
help_text="List of user identifiers that were not found or are invalid",
)
summary = UserValidationSummarySerializer(help_text="Summary statistics for the validation operation")