Skip to content

Conversation

@shaohuzhang1
Copy link
Contributor

feat: Tag permission interface

@f2c-ci-robot
Copy link

f2c-ci-robot bot commented Oct 22, 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-sigs/prow repository.

@f2c-ci-robot
Copy link

f2c-ci-robot bot commented Oct 22, 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

[PermissionConstants.KNOWLEDGE.get_workspace_knowledge_permission()], CompareConstants.AND),
)
@log(
menu='tag', operate="Batch Delete knowledge tag",
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 are several issues and optimizations that can be addressed in this Python code:

  1. Imports Optimization: Some imports are redundant. For example, ViewPermission is re-imported after being imported earlier. This can be reduced.

  2. Consistent Parameter Passing: Ensure consistent use of string templates for translations to avoid errors.

  3. Redundant Permissions Checks: If you want both WorkspaceManage-role and specific role permissions (like USER) for certain operations, it might make sense to combine them into a single permission check where feasible.

  4. Comments Clarification: Add comments if they're not already present to clarify the purpose of each method or function call.

Here's an optimized version with some corrections:

from common.auth import TokenAuth
from common.auth.authentication import has_permissions
from common.constants.permission_constants import (
    PermissionConstants,
    RoleConstants,
    ViewPermission,
    CompareConstants
)
from common.log.log import log
from common.result import result

class KnowledgeTagView(APIView):
    @method_decorator(has_permissions([
        PermissionConstants.KNOWLEDGE_TAG_CREATE.get_workspace_knowledge_permission(),
        RoleConstants.WORKSPACE_MANAGE.get_workspace_role(),
        ViewPermission(RoleConstants.USER.get_workspace_role(), 
                      [PermissionConstants.KNOWLEDGE.get_workspace_knowledge_permission()], 
                      CompareConstants.AND)
    ]))
    @method_decorator(log(menu='tag', operate="Create a knowledge tag"))
    def post(self, request: Request, workspace_id: str, knowledge_id: str) -> Response:
        return success()

def handle_tag_operations():
    """
    Handle various tag-related operations
    """

@handle_tag_operations.method_decorator(has_permissions([
    PermissionConstants.KNOWLEDGE_TAG_READ.get_workspace_knowledge_permission(),
    RoleConstants.WORKSPACE_MANAGE.get_workspace_role(),
    ViewPermission(RoleConstants.USER.get_workspace_role(), 
                  [PermissionConstants.KNOWLEDGE.get_workspace_knowledge_permission()], 
                  CompareConstants.AND)
]))
@handle_tag_operations.method_decorator(log(menu='tag', operate="Read a knowledge tag"))
def get_tags(request: Request, workspace_id: str, knowledge_id: str) -> Response:
    return success()

@handle_tag_operations.method_decorator(has_permissions([
    PermissionConstants.KNOWLEDGE_TAG_EDIT.get_workspace_knowledge_permission(),
    RoleConstants.WORKSPACE_MANAGE.get_workspace_role(),
    ViewPermission(RoleConstants.USER.get_workspace_role(), 
                  [PermissionConstants.KNOWLEDGE.get_workspace_knowledge_permission()], 
                  CompareConstants.AND)
]))
@handle_tag_operations.method_decorator(log(menu='tag', operate="Edit a knowledge tag"))
def edit_tags(request: Request, workspace_id: str, knowledge_id: str) -> Response:
    return success()

# Similar functions will be created similarly...

Key Changes Made:

  • Reduced redundancy in imports.
  • Consolidated identical logic across methods using decorators in Django viewset-style methods (APIView.post, etc.).
  • Combined similar checks into a single decorator call when applicable.

This refactoring improves maintainability and reduces chances for errors caused by duplicated logic.

)
RESOURCE_KNOWLEDGE_HIT_TEST = Permission(
group=Group.SYSTEM_RES_KNOWLEDGE_HIT_TEST, operate=Operate.READ, role_list=[RoleConstants.ADMIN],
parent_group=[SystemGroup.RESOURCE_KNOWLEDGE], is_ee=settings.edition == "EE"
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In this review of the provided Python code, I identify several areas that could be improved:

  1. Duplicate Tag Entries: The Operate.TAG enumeration has two entries with identical values (READ+TAG). This redundancy can lead to confusion and unexpected behavior throughout the application.

  2. Documentation Issues:

    • Some enumerations lack proper documentation comments to explain what each value represents.
    • The function get_workspace_role uses strings like 'resource authorization', which do not match the Enum names used in other parts of the code (e.g., Auth.value.
  3. Suggestion: Consistency with casing should be standardized across all references within the same file. For example, using lower-case naming consistently for enums might improve readability and maintainability.

  4. Enum Naming Conventions: It's recommended to follow PEP 8 guidelines for variable and function naming consistency and clarity.

  5. Comments: Adding more detailed comments about the purpose or intent behind certain actions could help clarify the logic flow.

Suggestions

Suggestion 1: Remove Duplicates

Remove the duplicate entry for OPERATE.TAG. You can choose either one based on which fits better with your design choices.

class Operate(Enum):
    ...
    TAG = "READ+TAG"

Alternatively, combine the meaning into a singular tag-related operation if applicable instead:

class Operate(Enum):
    # existing operations
    TAG_SET = "SET+TAG"  # Example new operation combining setting an attribute
    ```

#### Suggestion 2: Improve Docstrings and Consistency
Ensure each enum and function/variable name follows consistent naming conventions. Update docstrings accordingly where necessary to reflect changes in naming conventions.

Example update:

```python
class Operate(Enum):
    """
    Types of operation permitted by members to access resources.
    
    READ: Allow access to information without modifying.
    WRITE: Modify the data.
    DELETE: Delete the record permanently.
    """

    TO_CHAT = "READ+TO_CHAT"  # Request assistance via a dialogue channel
    SETTING = "READ+SETTING"  # Set preferences related to specific functionalities
    DOWNLOAD = "READ+DOWNLOAD"  # Download a document or asset associated with the project
    AUTH = "READ+AUTH"  # Resource Authorization Operation

# Further updates... similar to above

By implementing these changes, you enhance code clarity, maintainability, and reduce potential errors introduced by redundant or inconsistent elements.

PermissionConstants.KNOWLEDGE_DOCUMENT_TAG.get_workspace_permission_workspace_manage_role(),
RoleConstants.WORKSPACE_MANAGE.get_workspace_role(),
ViewPermission([RoleConstants.USER.get_workspace_role()],
[PermissionConstants.KNOWLEDGE.get_workspace_knowledge_permission()],
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The code provided seems to be related to permissions management for tagging knowledge documents and tags within a system like Knowledge Base Documentation. Here are some observations:

  1. Variable Naming: The variable permission_constants is used multiple times, but it's unclear what kind of constants this represents without additional context. Ensure that this is correctly imported or defined.

  2. Duplicate Permissions: There seems to be two instances where similar permissions (READ, EDIT) are referenced twice with different permission methods (e.g., using get_workspace_knowledge_permission() and get_workspace_permission_workspace_manage_role(). This might lead to confusion if there aren't clear differences between them based on the intended functionality.

  3. Consistency with Permissions: Some functions use one permission method while others use another. Make sure these consistent across the codebase to avoid errors during runtime when permissions need to be checked consistently.

  4. ViewPermission Usage: It’s noted that roles can restrict access to certain operations through views. Ensure that every function checks required capabilities using can_user_view_document_with_permissions.

  5. Logging: Consider adding logging statements at strategic points in your APIs to help with debugging issues. This could involve capturing input parameters, output results, or error messages.

  6. Error Handling: Implement proper exception handling to manage errors gracefully rather than simply failing silently. You should catch exceptions such as permissionDenied errors, invalid inputs, network issues, etc., and handle them appropriately with informative error messages.

  7. Code Review: Conducting a review process among other developers can help identify patterns not immediately apparent by oneself or highlight inefficiencies in structure and logic.

Overall, ensure clarity in terms of role permissions, consistency in implementation practices, and thorough testing across all user interactions involved in managing annotations and tag associations for documentation items.

@zhanweizhang7 zhanweizhang7 merged commit c0ae784 into v2 Oct 22, 2025
4 of 6 checks passed
@zhanweizhang7 zhanweizhang7 deleted the pr@v2@feat_tag_permission branch October 22, 2025 02:18
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.

3 participants