|
66 | 66 | from openedx_learning.api.authoring_models import Component |
67 | 67 | from organizations.models import Organization |
68 | 68 | from xblock.core import XBlock |
| 69 | +from openedx_authz.api import assign_role_to_user_in_scope |
69 | 70 |
|
70 | 71 | from openedx.core.types import User as UserType |
71 | 72 |
|
@@ -159,6 +160,12 @@ class AccessLevel: |
159 | 160 | NO_ACCESS = None |
160 | 161 |
|
161 | 162 |
|
| 163 | +ACCESS_LEVEL_TO_LIBRARY_ROLE = { |
| 164 | + AccessLevel.ADMIN_LEVEL: "library_admin", |
| 165 | + AccessLevel.AUTHOR_LEVEL: "library_author", |
| 166 | +} |
| 167 | + |
| 168 | + |
162 | 169 | @dataclass(frozen=True) |
163 | 170 | class ContentLibraryPermissionEntry: |
164 | 171 | """ |
@@ -534,6 +541,30 @@ def set_library_user_permissions(library_key: LibraryLocatorV2, user: UserType, |
534 | 541 | ) |
535 | 542 |
|
536 | 543 |
|
| 544 | +def assign_library_role_to_user(library_key: LibraryLocatorV2, user: UserType, access_level: str): |
| 545 | + """Grant a role to the specified user for this library. |
| 546 | +
|
| 547 | + Args: |
| 548 | + library_key (LibraryLocatorV2): The key of the content library. |
| 549 | + user (UserType): The user to whom the role will be granted. |
| 550 | + access_level (str | None): The access level to be granted. This access level maps to a specific role. |
| 551 | +
|
| 552 | + Raises: |
| 553 | + TypeError: If the user is an instance of AnonymousUser. |
| 554 | + """ |
| 555 | + if isinstance(user, AnonymousUser): |
| 556 | + raise TypeError("Invalid user type") |
| 557 | + |
| 558 | + role = ACCESS_LEVEL_TO_LIBRARY_ROLE.get(access_level) |
| 559 | + if role is None: |
| 560 | + raise ValueError(f"Invalid access level: {access_level}") |
| 561 | + |
| 562 | + if assign_role_to_user_in_scope(user.username, role, str(library_key)): |
| 563 | + log.info(f"Assigned role '{role}' to user '{user.username}' for library '{library_key}'") |
| 564 | + else: |
| 565 | + log.warning(f"Failed to assign role '{role}' to user '{user.username}' for library '{library_key}'") |
| 566 | + |
| 567 | + |
537 | 568 | def set_library_group_permissions(library_key: LibraryLocatorV2, group, access_level: str): |
538 | 569 | """ |
539 | 570 | Change the specified group's level of access to this library. |
|
0 commit comments