-
Notifications
You must be signed in to change notification settings - Fork 6
feat: adding bulk user validation endpoint for admin console #245
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 1 commit
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -4,6 +4,6 @@ | |
|
|
||
| import os | ||
|
|
||
| __version__ = "1.5.0" | ||
| __version__ = "1.6.0" | ||
|
|
||
| ROOT_DIRECTORY = os.path.dirname(os.path.abspath(__file__)) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -42,6 +42,8 @@ | |
| RemoveUsersFromRoleWithScopeSerializer, | ||
| TeamMemberSerializer, | ||
| UserRoleAssignmentSerializer, | ||
| UserValidationAPIViewResponseSerializer, | ||
| UserValidationAPIViewSerializer, | ||
| ) | ||
| from openedx_authz.utils import get_user_by_username_or_email | ||
|
|
||
|
|
@@ -586,3 +588,86 @@ def get(self, request: HttpRequest) -> Response: | |
| paginator = self.pagination_class() | ||
| paginated_response_data = paginator.paginate_queryset(team_members, request) | ||
| return paginator.get_paginated_response(paginated_response_data) | ||
|
|
||
|
|
||
| @view_auth_classes() | ||
| class UserValidationAPIView(APIView): | ||
| """API view for validating that provided user identifiers correspond to existing users. | ||
|
|
||
| This view allows clients to verify that a list of user identifiers (usernames or emails) | ||
| correspond to valid users in the system. It is designed to support bulk validation of multiple | ||
| user identifiers in a single request, providing a convenient way to check the validity of users before | ||
| performing operations such as role assignments. | ||
|
|
||
| **Endpoints** | ||
| - POST: Validate that the provided list of usernames or emails correspond to existing users | ||
|
|
||
| **Request Format (POST)** | ||
| - users: List of user identifiers (username or email) | ||
|
|
||
| **Response Format (POST)** | ||
|
|
||
| Returns HTTP 200 OK with:: | ||
|
|
||
| { | ||
| "valid_users": ["john_doe", "[email protected]"], | ||
| "invalid_users": ["nonexistent_user"], | ||
| "summary": { | ||
| "total": 3, | ||
| "valid_count": 2, | ||
| "invalid_count": 1 | ||
| } | ||
| } | ||
|
|
||
| **Authentication and Permissions** | ||
|
|
||
| - Requires authenticated user. | ||
| - Requires ``manage_library_team`` or ``manage_course_team`` permission in any scope. | ||
|
|
||
| **Example Request** | ||
|
|
||
| POST /api/authz/v1/users/validate/ :: | ||
|
|
||
| { | ||
| "users": ["john_doe", "[email protected]", "nonexistent_user"] | ||
| } | ||
| """ | ||
|
|
||
| permission_classes = [AnyScopePermission] | ||
|
|
||
| @apidocs.schema( | ||
| body=UserValidationAPIViewSerializer, | ||
| responses={ | ||
| status.HTTP_200_OK: UserValidationAPIViewResponseSerializer, | ||
| status.HTTP_400_BAD_REQUEST: "The request data is invalid", | ||
| status.HTTP_401_UNAUTHORIZED: "The user is not authenticated", | ||
| status.HTTP_403_FORBIDDEN: "The user does not have the required permissions", | ||
|
jacobo-dominguez-wgu marked this conversation as resolved.
|
||
| status.HTTP_500_INTERNAL_SERVER_ERROR: "An unexpected error occurred while validating users", | ||
| }, | ||
| ) | ||
| @authz_permissions([permissions.MANAGE_LIBRARY_TEAM.identifier, permissions.COURSES_MANAGE_COURSE_TEAM.identifier]) | ||
| def post(self, request: HttpRequest) -> Response: | ||
| """Validates the provided usernames or emails correspond to existing users.""" | ||
| request_serializer = UserValidationAPIViewSerializer(data=request.data) | ||
| request_serializer.is_valid(raise_exception=True) | ||
| serialized_request_users = request_serializer.validated_data["users"] | ||
| try: | ||
| valid_users, invalid_users = api.validate_users(serialized_request_users) | ||
| except Exception as e: # pylint: disable=broad-exception-caught | ||
| logger.error(f"Error validating users: {e}") | ||
| return Response( | ||
| data={"message": "An error occurred while validating users"}, | ||
| status=status.HTTP_500_INTERNAL_SERVER_ERROR, | ||
| ) | ||
|
|
||
| response_data = { | ||
| "valid_users": valid_users, | ||
| "invalid_users": invalid_users, | ||
| "summary": { | ||
| "total": len(serialized_request_users), | ||
| "valid_count": len(valid_users), | ||
| "invalid_count": len(invalid_users), | ||
| }, | ||
| } | ||
|
rodmgwgu marked this conversation as resolved.
|
||
| response_serializer = UserValidationAPIViewResponseSerializer(response_data) | ||
| return Response(response_serializer.data, status=status.HTTP_200_OK) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,9 @@ | ||
| """Test suite for user-role assignment API functions.""" | ||
|
|
||
| from unittest.mock import patch | ||
|
|
||
| from ddt import data, ddt, unpack | ||
| from django.contrib.auth import get_user_model | ||
|
|
||
| from openedx_authz.api.data import ContentLibraryData, RoleAssignmentData, RoleData, UserData | ||
| from openedx_authz.api.users import ( | ||
|
|
@@ -14,6 +17,7 @@ | |
| is_user_allowed, | ||
| unassign_all_roles_from_user, | ||
| unassign_role_from_user, | ||
| validate_users, | ||
| ) | ||
| from openedx_authz.constants import permissions, roles | ||
| from openedx_authz.constants.roles import LIBRARY_ADMIN_PERMISSIONS, LIBRARY_AUTHOR_PERMISSIONS | ||
|
|
@@ -514,3 +518,55 @@ def test_is_user_allowed(self, username, action, scope_name, expected_result): | |
| scope_external_key=scope_name, | ||
| ) | ||
| self.assertEqual(result, expected_result) | ||
|
|
||
|
|
||
| @ddt | ||
| class TestValidateUsersAPI(UserAssignmentsSetupMixin): | ||
| """Test suite for validate_users API function - focused on business logic.""" | ||
|
|
||
| def test_validate_users_empty_list(self): | ||
| """Test validate_users with empty input list.""" | ||
| valid_users, invalid_users = validate_users([]) | ||
|
|
||
| self.assertEqual(valid_users, []) | ||
| self.assertEqual(invalid_users, []) | ||
|
|
||
| def test_validate_users_inactive_user_edge_case(self): | ||
| """Test that inactive users are correctly identified as invalid.""" | ||
| User = get_user_model() | ||
|
|
||
| # Create an inactive user for this test | ||
| inactive_user = User.objects.create_user( | ||
| username="inactive_api_test", email="[email protected]", is_active=False | ||
| ) | ||
|
|
||
| valid_users, invalid_users = validate_users([inactive_user.username]) | ||
|
|
||
| # Cleanup | ||
| inactive_user.delete() | ||
|
|
||
| self.assertEqual(valid_users, []) | ||
| self.assertEqual(invalid_users, [inactive_user.username]) | ||
|
|
||
| @patch("openedx_authz.api.users.get_user_by_username_or_email") | ||
| def test_validate_users_unexpected_exception_propagation(self, mock_get_user): | ||
| """Test that unexpected exceptions from get_user_by_username_or_email are re-raised.""" | ||
| # Simulate an unexpected database error | ||
| mock_get_user.side_effect = Exception("Database connection lost") | ||
|
|
||
| with self.assertRaises(Exception) as cm: | ||
| validate_users(["any_user"]) | ||
|
|
||
| self.assertEqual(str(cm.exception), "Database connection lost") | ||
| mock_get_user.assert_called_once_with("any_user") | ||
|
|
||
| @patch("openedx_authz.api.users.get_user_by_username_or_email") | ||
| def test_validate_users_user_does_not_exist_handling(self, mock_get_user): | ||
| """Test handling of User.DoesNotExist exception.""" | ||
| User = get_user_model() | ||
| mock_get_user.side_effect = User.DoesNotExist("User not found") | ||
|
|
||
| valid_users, invalid_users = validate_users(["nonexistent_user"]) | ||
|
|
||
| self.assertEqual(valid_users, []) | ||
| self.assertEqual(invalid_users, ["nonexistent_user"]) | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.