|
1 | 1 | """Utility functions for the Open edX AuthZ REST API.""" |
2 | 2 |
|
3 | 3 | import logging |
4 | | -from dataclasses import dataclass |
5 | 4 |
|
6 | 5 | from django.contrib.auth import get_user_model |
7 | 6 |
|
|
13 | 12 | OrgCourseOverviewGlobData, |
14 | 13 | RoleAssignmentData, |
15 | 14 | ScopeData, |
| 15 | + UserAssignments, |
16 | 16 | ) |
17 | 17 | from openedx_authz.api.users import is_user_allowed |
18 | 18 | from openedx_authz.constants.permissions import COURSES_VIEW_COURSE, VIEW_LIBRARY |
19 | | -from openedx_authz.rest_api.data import SearchField, SortField, SortOrder |
| 19 | +from openedx_authz.rest_api.data import SearchField, SortField, SortOrder, UserAssignmentsFilter |
20 | 20 |
|
21 | 21 | logger = logging.getLogger(__name__) |
22 | 22 |
|
@@ -131,12 +131,6 @@ def filter_users(users: list[dict], search: str | None, roles: list[str] | None) |
131 | 131 | return filtered_users |
132 | 132 |
|
133 | 133 |
|
134 | | -@dataclass |
135 | | -class UserAssignments: |
136 | | - user: "User" |
137 | | - assignments: list[RoleAssignmentData] |
138 | | - |
139 | | - |
140 | 134 | def get_user_assignment_map(role_assignments: list[RoleAssignmentData]) -> list[UserAssignments]: |
141 | 135 | """ |
142 | 136 | Group role assignments by user |
@@ -175,3 +169,33 @@ def filter_allowed_assignments(user: "User", assignments: list[RoleAssignmentDat |
175 | 169 | allowed_assignments.append(assignment) |
176 | 170 |
|
177 | 171 | return allowed_assignments |
| 172 | + |
| 173 | + |
| 174 | +def filter_user_assignments( |
| 175 | + users_with_assignments: list[UserAssignments], |
| 176 | + by: UserAssignmentsFilter, |
| 177 | + values: list[str], |
| 178 | +) -> list[UserAssignments]: |
| 179 | + """ |
| 180 | + Filter user assignments by orgs or scopes. |
| 181 | + """ |
| 182 | + if not values: |
| 183 | + return users_with_assignments |
| 184 | + |
| 185 | + def _get_value_to_filter(assignment: RoleAssignmentData) -> str: |
| 186 | + if by == UserAssignmentsFilter.SCOPES: |
| 187 | + return assignment.scope.external_key |
| 188 | + elif by == UserAssignmentsFilter.ORGS: |
| 189 | + return assignment.scope.org |
| 190 | + else: |
| 191 | + raise ValueError(f"Invalid filter: '{by}'. Must be one of {UserAssignmentsFilter.values()}") |
| 192 | + |
| 193 | + filtered_users: list[UserAssignments] = [] |
| 194 | + for uwa in users_with_assignments: |
| 195 | + if any(_get_value_to_filter(a) in values for a in uwa.assignments): |
| 196 | + # Also filter assignments to reflect the correct number of assignments |
| 197 | + filtered_assignments = [a for a in uwa.assignments if _get_value_to_filter(a) in values] |
| 198 | + filtered_users.append(UserAssignments(user=uwa.user, assignments=filtered_assignments)) |
| 199 | + users_with_assignments = filtered_users |
| 200 | + |
| 201 | + return filtered_users |
0 commit comments