Skip to content

Conversation

@shaohuzhang1
Copy link
Contributor

feat: User profile returns permission role information

@f2c-ci-robot
Copy link

f2c-ci-robot bot commented Apr 27, 2025

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.

Details

Instructions 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.

@f2c-ci-robot
Copy link

f2c-ci-robot bot commented Apr 27, 2025

[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.

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

'permissions': auth.permission_list,
'is_edit_password': user.password == 'd880e722c47a34d8e9fce789fc62389d' if user.role == 'ADMIN' else False,
'language': user.language}

Copy link
Contributor Author

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:

  1. Duplicate Import: The Auth class is being imported twice from common.constants.auth, which can cause conflicts.

  2. Unused Code: The commented-out section inside the profile method suggests that some functionality might have been intended but was removed.

  3. Inconsistent Formatting: There's inconsistent indentation throughout the file, which makes it harder to read and maintain.

  4. Lack of Type Hinting for Parameters: Some parameters (like user) are not type-hinted correctly, making it less discoverable what types they expect.

  5. Potential Security Issue: If user.password is hardcoded ('d880e722c47a34d8e9fce789fc62389d') and used directly without hashing or comparing, it could lead to security vulnerabilities.

  6. 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 (user and auth) are properly typed.
  • Included checks for attribute existence before accessing role_list and permission_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


Copy link
Contributor Author

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
  1. The permission_list is now specified using Union, which allows it to be either a list of PermissionConstants or List[Any]. This might be appropriate depending on your context, but ensure that all elements in the list implement the necessary methods or interfaces.

  2. Replaced the comma , with an underscore _ before **keywords to 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.

@shaohuzhang1 shaohuzhang1 merged commit c79479d into v2 Apr 27, 2025
3 of 4 checks passed
@shaohuzhang1 shaohuzhang1 deleted the pr@v2@feat_user_permission branch April 27, 2025 10:27
return result.success(UserProfileSerializer().profile(request.user, request.auth))


class UserManage(APIView):
Copy link
Contributor Author

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:

  1. Consistency: In your APIView classes (UserProfileView, TestPermissionsUserView, TestWorkspacePermissionUserView, UserManage), you are adding permissions using different decorators and syntaxes. It's better to standardize this for consistency.

  2. 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.

  3. 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:

  1. Abstracted Common Code: Encapsulated common functionality in BaseUserProfileView.
  2. Consistent API Design: Consistently use JSONResponse instead of plain returns where applicable.
  3. Detailed Error Handling: Added basic validation errors handling for POST operations.
  4. 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants