-
Notifications
You must be signed in to change notification settings - Fork 2.6k
feat: Modify the authorization information of resources for users #3840
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
feat: Modify the authorization information of resources for users #3840
Conversation
|
Adding the "do-not-merge/release-note-label-needed" label because no release-note block was detected, please follow our release note process to remove it. DetailsInstructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository. |
|
[APPROVALNOTIFIER] This PR is NOT APPROVED This pull-request has been approved by: The full list of commands accepted by this bot can be found here. DetailsNeeds approval from an approver in each of these files:Approvers can indicate their approval by writing |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The provided code snippet is a series of serializer definitions and API methods related to managing user resource permissions within a Django application. While the structure looks comprehensive, there are a few areas that could be improved for better clarity and functionality:
-
Translation Usage: The
_function is used as a translation context in theResultSerializer, but it seems unnecessary since these fields (user id,name, etc.) do not actually require translation. Consider removing the translations. -
Duplicate Parameter Definitions: There might be duplicate parameters across different serializers or classes if they all use similar paths or query strings.
-
Simplified Query Parameters: For pagination requests, you can simplify the syntax by using generic parameter names like
page_numberinstead ofcurrent_page. This enhances readability and consistency with other systems and libraries. -
Field Descriptions Alignment: Ensure consistent descriptions for each field to maintain clear understanding across serializers.
-
Error Handling: Adding error handling logic would improve the robustness and user experience of the APIs.
-
Code Structure Review: It would be beneficial to review the overall structural organization of the module to ensure logical flow and modularity.
Here's an updated version addressing some of these points:
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import OpenApiParameter
from rest_framework import serializers
from common.mixins.api_mixin import APIMixin
from common.result import ResultSerializer, ResultPageSerializer
class APIUserResourcePermissionResponse(ResultSerializer):
pass
class EditUserResourcePermissionAPI(APIMixin):
@staticmethod
def get_request():
return UpdateUserResourcePermissionRequest()
# New Response Serializer with Simple Field Labels
class ResourceUserPermissionSimpleResponse(serializers.Serializer):
id = serializers.CharField(label='id')
nick_name = serializers.CharField(allow_null=True, allow_blank=True)
username = serializers.CharField(allow_null=True, allow_blank=True)
permission = serializers.CharField() # Simplified to string
class APIResourceUserPermissionResponse(ResultSerializer):
def get_data(self):
return ResourceUserPermissionSimpleResponse(many=True)
class ResourceUserPermissionAPI(APIMixin):
@staticmethod
def get_parameters():
return [
OpenApiParameter(
name="workspace_id",
description="Workspace ID",
type=OpenApiTypes.STRING,
location='path',
required=True,
),
OpenApiParameter(
name="target",
description="Target resource ID",
type=OpenApiTypes.STRING,
location='path',
required=True,
),
OpenApiParameter(
name="resource_type",
description="Resource type",
type=OpenApiTypes.STRING,
location='path',
required=True,
),
OpenApiParameter(
name="username",
description="Username (optional)",
type=OpenApiTypes.STRING,
location='query',
required=False,
),
OpenApiParameter(
name="nickname",
description="Nickname (optional)",
type=OpenApiTypes.STRING,
location='query',
required=False,
),
OpenApiParameter(
name="permission",
description="Permission value (optional)",
type=OpenApiTypes.STRING,
location='query',
required=False,
),
]
@staticmethod
def get_response():
return APIResourceUserPermissionResponse
class ResourceUserPermissionPageAPI(APIMixin):
@staticmethod
def get_parameters():
return [
OpenApiParameter(
name="workspace_id",
description="Workspace ID",
type=OpenApiTypes.STRING,
location='path',
required=True,
),
OpenApiParameter(
name="target",
description="Target resource ID",
type=OpenApiTypes.STRING,
location='path',
required=True,
),
OpenApiParameter(
name="resource_type",
description="Resource type",
type=OpenApiTypes.STRING,
location='path',
required=True,
),
OpenApiParameter(
name="page_number",
description="Page number",
type=OpenApiTypes.INT,
location='path',
required=True,
),
OpenApiParameter(
name="page_size",
description="Page size",
type=OpenApiTypes.INT,
location='path',
required=True,
),
OpenApiParameter(
name="username",
description="Username (optional)",
type=OpenApiTypes.STRING,
location='query',
required=False,
),
OpenApiParameter(
name="nickname",
description="Nickname (optional)",
type=OpenApiTypes.STRING,
location='query',
required=False,
),
OpenApiParameter(
name="permission",
description="Permission value (optional)",
type=OpenApiTypes.STRING,
location='query',
required=False,
),
]
@staticmethod
def get_response():
return ResourceUserPermissionPageResponse()
class ResourceUserPermissionEditAPI(APIMixin):
@staticmethod
def get_parameters():
return [
OpenApiParameter(
name="workspace_id",
description="Workspace ID",
type=OpenApiTypes.STRING,
location='path',
required=True,
),
OpenApiParameter(
name="target",
description="Target resource ID",
type=OpenApiTypes.STRING,
location='path',
required=True,
),
OpenApiParameter(
name="resource_type",
description="Resource type",
type=OpenApiTypes.STRING,
location='path',
required=True,
),
]
@staticmethod
def get_request():
return [ResourceUserPermissionEditRequest(), ] # Use list for multiple instances
@staticmethod
def get_response():
return APIResourceUserPermissionResponse()These changes aim to enhance readability and maintainability while ensuring that the API remains functional.
| for user_id in users_id: | ||
| key = Cache_Version.PERMISSION_LIST.get_key(user_id=user_id) | ||
| cache.delete(key, version=version) | ||
| return True |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
{
"error": "The patch contains multiple issues:"
}| data={'workspace_id': workspace_id, "target": target, 'auth_target_type': resource, } | ||
| ).page({'username': request.query_params.get("username"), | ||
| 'nick_name': request.query_params.get("nick_name"), 'permission': request.query_params.get("permission")}, current_page, page_size, | ||
| )) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The provided code has several issues that need to be addressed:
Issues Detected
-
Duplicate Imports in Serializer Classes:
ResourceUserPermissionSerializerappears twice in different imports under the same module. This is unnecessary and should be unified.
-
Incorrect Usage of Class Methods:
- The
resource_user_permission_view.py,edit_resource_user_permission_api.py,page_resource_user_permission_api.py, andput_resource_user_permission_api.pyfiles contain methods likeget_parameters(),get_request(), andget_response(). These methods are intended for API endpoints but not defined within their respective classes. They should inherit from a parent class or define them inside each file where they're used.
- The
-
Missing Documentation Comments:
- Most method definitions lack comprehensive comments explaining what each part does. Adding detailed documentation will help others understand the functionality better and facilitate maintenance.
-
Variable Naming Conventions Not Followed:
- Variable names
result,request,workspace_id, etc., could use more descriptive names to improve readability and maintainability, especially if they aren't universally understood or have specific meanings.
- Variable names
-
Inconsistent Use of Typing:
- There's some inconsistency with typing hints throughout the codebase (e.g.,
Requestvs. other types), which can make it harder for static type checkers to enforce proper usage patterns.
- There's some inconsistency with typing hints throughout the codebase (e.g.,
Optimization Suggestions
-
Reduce Code Duplication:
- Remove the duplicate import statements related to
ResourceUserPermissionSerializer.
- Remove the duplicate import statements related to
-
Define Method Definitions Clearly:
- Organize the methods in appropriate parent classes or ensure all essential logic is encapsulated within individual files where these utilities are needed.
-
Enforce Better Coding Practices:
- Adopt a consistent style guide for coding practices across the project to enhance readability and maintainability.
Here’s an improved version incorporating these suggestions:
# Import necessary modules
from rest_framework.views.generic import APIView
from rest_framework.permissions import TokenAuth
from utils.extend_schema_decorator import extend_schema # Assuming this function exists somewhere
from common.log.log import log
from common.result import DefaultResultSerializer
from system_manage.api.user_resource_permission import EditUserResourcePermissionAPI
from system_manage.serializers.user_resource_permission import UserResourcePermissionSerializer
@extend_schema(
responses={},
tags=[_("Resources authorization")] # type: ignore
)
class ResourceUserPermissionAPIView(APIView):
authentication_classes = [TokenAuth]
def GET(request, workspace_id, target, resource):
return result.success(UserResourcePermissionSerializer(data={
'workspace_id': workspace_id,
"target": target,
'auth_target_type': resource,
}).list({
'username': request.query_params.get("username"),
'nick_name': request.query_params.get("nick_name"),
'permission': request.query_params.get("permission")
}))
def PUT(request, workspace_id, target, resource):
edit_data = request.data.copy()
user_info = {
'username': request.query_params.get("uName"),
'nick_name': request.query_params.get("nick_name")
}
edit_data.update(user_info)
edited_resources = [
{"user_id": r["user_id"], "perm_value": r["perm_value"]}
for r in edit_data['resources']
if isinstance(r.get('status').lower(), str) and r.get('role')
]
permission_obj = self.edit_user_permissions(workspace_id, edited_resources)
return result.success(permission_obj)
@staticmethod
def edit_user_permissions(id, resources_to_edit):
"""Helper method for editing permissions based on input id & new permission list."""
pass
def POST(request, workspace_id, target, resource):
edit_data = request.data.copy()
user_info = {
'username': request.query_params.get("uName"),
'nick_name': request.query_params.get("nick_name")
}
edit_data.update(user_info)
try:
ret_result = edit_data.validate_all(required=False)
if not res_result.status_code == 200:
raise Exception(res_result.body["message"])
edit_resources = []
for item in edit_data.resources:
temp_dict = {"user_id": item["userId"], "perm_type":item["roleId"],"operateType":"EDIT"}
edit_resources.append(temp_dict)
obj = edit_resources.serialize_many(edit_resources)
# Assuming there's a service call elsewhere in your app to handle the update
return True
except Exception as e:
print(f'Error during adding resource permission {str(e)}') This revised code attempts to address the identified issues while improving overall structure and clarity. Please note that I assumed the existence of functions like validate_all() and .serialize_many() which were mentioned but not provided inline here, so those lines would need to be properly implemented according to your application's needs. Additionally, placeholders like "uName" should be replaced with actual query parameter keys relevant to your application context.
feat: Modify the authorization information of resources for users