|
| 1 | +"""Utility functions for the Open edX AuthZ REST API.""" |
| 2 | + |
| 3 | +from django.contrib.auth import get_user_model |
| 4 | +from django.db.models import Q |
| 5 | +from edx_rest_framework_extensions.auth.jwt.authentication import JwtAuthentication |
| 6 | +from edx_rest_framework_extensions.auth.session.authentication import SessionAuthenticationAllowInactiveUser |
| 7 | +from rest_framework.permissions import IsAuthenticated |
| 8 | + |
| 9 | +from openedx_authz.rest_api.enums import SearchField, SortField, SortOrder |
| 10 | + |
| 11 | +User = get_user_model() |
| 12 | + |
| 13 | + |
| 14 | +def view_auth_classes(is_authenticated=True): |
| 15 | + """ |
| 16 | + Function and class decorator that abstracts the authentication and permission checks for api views. |
| 17 | + """ |
| 18 | + |
| 19 | + def _decorator(func_or_class): |
| 20 | + """ |
| 21 | + Requires either OAuth2 or Session-based authentication. |
| 22 | + """ |
| 23 | + func_or_class.authentication_classes = [ |
| 24 | + JwtAuthentication, |
| 25 | + SessionAuthenticationAllowInactiveUser, |
| 26 | + ] |
| 27 | + if is_authenticated: |
| 28 | + func_or_class.permission_classes.insert(0, IsAuthenticated) |
| 29 | + return func_or_class |
| 30 | + |
| 31 | + return _decorator |
| 32 | + |
| 33 | + |
| 34 | +def get_user_by_username_or_email(username_or_email: str) -> User: |
| 35 | + """ |
| 36 | + Retrieve a user by their username or email address. |
| 37 | +
|
| 38 | + Args: |
| 39 | + username_or_email (str): The username or email address to search for. |
| 40 | +
|
| 41 | + Returns: |
| 42 | + User: The User object if found and not retired. |
| 43 | +
|
| 44 | + Raises: |
| 45 | + User.DoesNotExist: If no user matches the provided username or email, |
| 46 | + or if the user has an associated retirement request. |
| 47 | + """ |
| 48 | + user = User.objects.get(Q(email=username_or_email) | Q(username=username_or_email)) |
| 49 | + if hasattr(user, "userretirementrequest"): |
| 50 | + raise User.DoesNotExist |
| 51 | + return user |
| 52 | + |
| 53 | + |
| 54 | +def sort_users( |
| 55 | + users: list[dict], sort_by: SortField = SortField.USERNAME, order: SortOrder = SortOrder.ASC |
| 56 | +) -> list[dict]: |
| 57 | + """ |
| 58 | + Sort users by a given field and order. |
| 59 | +
|
| 60 | + Args: |
| 61 | + users (list[dict]): The users to sort. |
| 62 | + sort_by (SortField, optional): The field to sort by. Defaults to SortField.USERNAME. |
| 63 | + order (SortOrder, optional): The order to sort by. Defaults to SortOrder.ASC. |
| 64 | +
|
| 65 | + Raises: |
| 66 | + ValueError: If the sort field is invalid. |
| 67 | + ValueError: If the sort order is invalid. |
| 68 | +
|
| 69 | + Returns: |
| 70 | + list[dict]: The sorted users. |
| 71 | + """ |
| 72 | + if sort_by not in SortField.values(): |
| 73 | + raise ValueError(f"Invalid field: '{sort_by}'. Must be one of {SortField.values()}") |
| 74 | + |
| 75 | + if order not in SortOrder.values(): |
| 76 | + raise ValueError(f"Invalid order: '{order}'. Must be one of {SortOrder.values()}") |
| 77 | + |
| 78 | + sorted_users = sorted(users, key=lambda user: (user.get(sort_by) or "").lower(), reverse=order == SortOrder.DESC) |
| 79 | + return sorted_users |
| 80 | + |
| 81 | + |
| 82 | +def filter_users(users: list[dict], search: str | None, roles: list[str] | None) -> list[dict]: |
| 83 | + """ |
| 84 | + Filter users by a case-insensitive search string and/or by roles. |
| 85 | +
|
| 86 | + Args: |
| 87 | + users (list[dict]): The users to filter. |
| 88 | + search (str | None): Optional search term matched against fields in ``SearchField``. |
| 89 | + roles (list[str] | None): Optional list of roles; include users that have any of these roles. |
| 90 | +
|
| 91 | + Returns: |
| 92 | + list[dict]: The filtered users, preserving the original order. |
| 93 | + """ |
| 94 | + if not search and not roles: |
| 95 | + return users |
| 96 | + |
| 97 | + filtered_users = [] |
| 98 | + for user in users: |
| 99 | + if search: |
| 100 | + matches_search = any(search in (user.get(field) or "").lower() for field in SearchField.values()) |
| 101 | + if not matches_search: |
| 102 | + continue |
| 103 | + |
| 104 | + if roles: |
| 105 | + matches_role = any(role in user.get("roles", []) for role in roles) |
| 106 | + if not matches_role: |
| 107 | + continue |
| 108 | + |
| 109 | + filtered_users.append(user) |
| 110 | + |
| 111 | + return filtered_users |
0 commit comments