Skip to content

Commit c4e07da

Browse files
committed
refactor: introduce helper function to extract org and course ID from AuthZ scope
1 parent 2168125 commit c4e07da

1 file changed

Lines changed: 26 additions & 12 deletions

File tree

common/djangoapps/student/roles.py

Lines changed: 26 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,27 @@ class AuthzCompatCourseAccessRole:
141141
role: str
142142

143143

144+
def _get_org_and_course_id_from_authz_scope(
145+
scope: CourseOverviewData | OrgCourseOverviewGlobData,
146+
) -> tuple[str, str | None] | None:
147+
"""
148+
Extract the org and course key from an AuthZ course assignment scope.
149+
150+
Course-scoped assignments return ``(org, course_external_key)``.
151+
Org-wide assignments return ``(org, None)``.
152+
153+
Returns ``None`` when the org cannot be determined. For org-wide scopes,
154+
``OrgGlobData.org`` is typed as ``str | None`` because it is parsed from
155+
``external_key`` and returns ``None`` for malformed glob patterns.
156+
"""
157+
if isinstance(scope, CourseOverviewData):
158+
course_id = scope.external_key
159+
return get_org_from_key(course_id), course_id
160+
if isinstance(scope, OrgCourseOverviewGlobData):
161+
return scope.org, None
162+
return None
163+
164+
144165
def authz_get_all_course_assignments_for_user(user: User) -> list[RoleAssignmentData]:
145166
"""
146167
Return AuthZ role assignments for a user that apply to courses.
@@ -182,20 +203,13 @@ def _compat_roles_from_authz_assignment(
182203
183204
Returns:
184205
set[AuthzCompatCourseAccessRole]: Legacy-compatible role records for the
185-
assignment. Returns an empty set if the scope is unsupported, the org
186-
is missing for an org-wide assignment, or no roles could be mapped.
206+
assignment. Returns an empty set if the org cannot be determined from
207+
the scope or no roles could be mapped.
187208
"""
188-
scope = assignment.scope
189-
if isinstance(scope, CourseOverviewData):
190-
course_id = scope.external_key
191-
org = get_org_from_key(course_id)
192-
elif isinstance(scope, OrgCourseOverviewGlobData):
193-
org = scope.org
194-
if not org:
195-
return set()
196-
course_id = None
197-
else:
209+
org_and_course_id = _get_org_and_course_id_from_authz_scope(assignment.scope)
210+
if org_and_course_id is None:
198211
return set()
212+
org, course_id = org_and_course_id
199213

200214
compat_roles = set()
201215
for role in assignment.roles:

0 commit comments

Comments
 (0)