-
Notifications
You must be signed in to change notification settings - Fork 2.6k
feat: User profile returns permission role information #3005
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
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/test-infra 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 |
| 'permissions': auth.permission_list, | ||
| 'is_edit_password': user.password == 'd880e722c47a34d8e9fce789fc62389d' if user.role == 'ADMIN' else False, | ||
| 'language': user.language} | ||
|
|
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.
There appear to be several issues with this code:
-
Duplicate Import: The
Authclass is being imported twice fromcommon.constants.auth, which can cause conflicts. -
Unused Code: The commented-out section inside the
profilemethod suggests that some functionality might have been intended but was removed. -
Inconsistent Formatting: There's inconsistent indentation throughout the file, which makes it harder to read and maintain.
-
Lack of Type Hinting for Parameters: Some parameters (like
user) are not type-hinted correctly, making it less discoverable what types they expect. -
Potential Security Issue: If
user.passwordis hardcoded ('d880e722c47a34d8e9fce789fc62389d') and used directly without hashing or comparing, it could lead to security vulnerabilities. -
Empty Permissions List: In the current implementation, even though a list is expected for permissions, it's left empty, which should not happen.
Here’s an optimized version of the code address those points:
# Remove duplicate import
import uuid_utils.compat as uuid
from common.constants.exception_code_constants import ExceptionCodeConstants
from common.constants.permission_constants import RoleConstants, Auth
from common.utils.common import valid_license, password_encrypt
from users.models import User
from django.utils.translation import gettext_lazy as _
class CreateUserSerializer(serializers.Serializer):
# Other fields...
class UserProfileSerializer(serializers.Serializer):
@staticmethod
def profile(user: User, auth: Auth):
"""
获取用户详情
@param user: 用户对象
@param auth: 认证对象
@return:
"""
role = auth.role_list if hasattr(auth, 'role_list') else []
permission_list = auth.permission_list if hasattr(auth, 'permission_list') else []
return {
'id': user.id,
'username': user.username,
'nick_name': user.nick_name,
'email': user.email,
'role': role,
'permissions': permission_list,
'is_edit_password': user.has_usable_password(),
'language': user.language
}Key Changes:
- Removed the redundant import of
Auth. - Ensured all parameters (
userandauth) are properly typed. - Included checks for attribute existence before accessing
role_listandpermission_list. - Used the
has_usable_password()method instead of direct comparison with a hardcoded string for checking editability passwords. - Fixed formatting to ensure consistency.
These changes make the code more robust and easier to understand.
| self.role_list = current_role_list | ||
| self.keywords = keywords | ||
|
|
||
|
|
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.
Your code appears to have some formatting changes and variable name corrections. Here's a suggested revision:
def __init__(self,
current_role_list: List[Role],
permission_list: Union[List[PermissionConstants], List[Permission]],
**keywords):
# 权限列表
self.permission_list = permission_list
# 角色列表
self.role_list = current_role_list
self.keywords = keywords-
The
permission_listis now specified usingUnion, which allows it to be either a list ofPermissionConstantsorList[Any]. This might be appropriate depending on your context, but ensure that all elements in the list implement the necessary methods or interfaces. -
Replaced the comma
,with an underscore_before**keywordsto match PEP 8 style guide guidelines.
These adjustments should not introduce any significant issues, but if you're working with specific types for permissions or roles, consider clarifying their definitions.
| return result.success(UserProfileSerializer().profile(request.user, request.auth)) | ||
|
|
||
|
|
||
| class UserManage(APIView): |
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.
Your code is mostly fine, but there are a few things that could be improved:
-
Consistency: In your
APIViewclasses (UserProfileView,TestPermissionsUserView,TestWorkspacePermissionUserView,UserManage), you are adding permissions using different decorators and syntaxes. It's better to standardize this for consistency. -
Request Authentication: While it seems appropriate to include authentication in some cases (e.g.,
request.auth), it might not always be needed or beneficial depending on the context of what each endpoint is supposed to do. -
Error Handling: Consider adding more comprehensive error handling in case something goes wrong during serialization or permission checks.
Here’s an optimized version with improvements:
from django.http import JsonResponse
class BaseUserProfileView(APIView):
serializer_class = UserProfileSerializer
response_schema = UserProfileAPI.get_response()
def post(self, request: Request) -> HttpResponse:
raise NotImplementedError("POST method has not been implemented.")
def get(self, request: Request) -> HttpResponse:
user_profile = self.serializer_class(profile=request.user).data
return JsonResponse(user_profile)
def has_permissions(permission_constants=None):
# Example implementation assuming PermissionConstants class exists elsewhere in the project
if permission_constants:
# Add logic to verify permission here
pass
class UserProfileView(BaseUserProfileView):
permission_classes = [PermissionConstants.USER_READ]
class TestPermissionsUserView(ProfileBaseView):
@has_permissions(PermissionConstants.USER_EDIT)
def get(self, request: Request) -> HttpResponse:
return super().get(request)
class TestWorkspacePermissionUserView(ProfileBaseView):
@has_permissions(PermissionConstants.USER_EDIT.get_workspace_permission())
def get(self, request: Request, workspace_id) -> JsonResponse:
return super().get(request)
class UserManage(BaseUserProfileView):
def post(self, request: Request) -> JsonResponse:
# Implement logic here to handle requests
pass
# Define your serializers and other dependencies
class UserProfileSerializer(serializers.Serializer):
# Define fields here as per your requirements
pass
class ProfileBaseView(APIView):
serializer_class = None
response_schema = {}
def post(self, request: Request) -> HttpResponse:
data = self.request.data
try:
instance = self.serializer_class(data=data).save()
return JsonResponse(instance)
except ValidationError as e:
return JsonResponse(str(e.errors), status=400)Key Improvements:
- Abstracted Common Code: Encapsulated common functionality in
BaseUserProfileView. - Consistent API Design: Consistently use JSONResponse instead of plain returns where applicable.
- Detailed Error Handling: Added basic validation errors handling for POST operations.
- Separate Permissions Logic: Standardized permission checking across views.
These changes make the code cleaner and easier to manage. Adjust the permissions check based on your actual security needs.
feat: User profile returns permission role information