Skip to content

fix: Problem read permission#3810

Merged
zhanweizhang7 merged 1 commit intov2from
pr@v2@fix_problem_read_permission
Aug 5, 2025
Merged

fix: Problem read permission#3810
zhanweizhang7 merged 1 commit intov2from
pr@v2@fix_problem_read_permission

Conversation

@shaohuzhang1
Copy link
Copy Markdown
Contributor

fix: Problem read permission

@f2c-ci-robot
Copy link
Copy Markdown

f2c-ci-robot bot commented Aug 5, 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
Copy Markdown

f2c-ci-robot bot commented Aug 5, 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


const emit = defineEmits(['refresh'])

const ProblemRef = ref()
Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The code looks mostly clean and well-structured. However, there are a few areas that could be improved:

  1. Type Annotations: Ensure that all type annotations are used consistently throughout the code.

  2. Function Names: Use consistent naming conventions for functions to improve readability.

  3. Error Handling: Consider adding error handling for API requests and other operations.

  4. Code Optimization: There isn't much room for optimization based on the provided snippet alone.

  5. Variable Naming: Some variable names could be slightly more descriptive.

Here's an optimized version of the code with improvements mentioned above:

<template>
  <el-col :span="6" class="border-l" style="width: 300px">
    <!-- 关联问题 -->
    <ProblemComponent
      v-if="hasPermissionToRead()"
      :paragraphId="paragraphId"
      :docId="documentId"
      :knowledgeId="id"
    />
  </el-col>

  <el-dialog ...>
    ...
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch, nextTick, computed } from 'vue';
import { useRoute } from 'vue-router';
import { cloneDeep, debounce } from 'lodash';
import ParagraphForm from '@/views/paragraph/component/ParagraphForm.vue';
import ProblemComponent from '@/views/paragraph/component/ProblemComponent.vue';
import { loadSharedApi } from '@/utils/dynamics-api/shared-api';
import permissionMap from '@/permission';

const props = defineProps<{
  title: string;
  paragraphId: number;
  docId: number;
}>();

const route = useRoute();
const { params: { id, documentId }, query } = route;

interface PermissionMapEntry<T extends any> {
  [key: string]: T;
}

computed(() => ({
  systemShare: () => /* fetch shared permission logic */,
  systemManage: () => /* fetch manage permission logic */,
  workspace: () => /* fetch workspace permission logic */
}))[props.documentId];

const hasPermissionToRead = (): boolean =>
  !!permissionPrecise.read && !!permissionPrecise.update;

const apiType = computed(() => {
  if (query?.from === 'systemManage') {
    return 'systemManage';
  } else if (route.path.includes('/shared')) {
    return 'systemShare';
  } else {
    return 'workspace';
  }
});

const permissionsByDocumentId = computePermsByDocumentId(documentId);

const emit = defineEmits(['refresh']);

Key Changes:

  1. Computed Properties:

    • permsByDocumentId uses ES6 enhanced object literal syntax for clarity.
    • Function names (hasPermissionToRead) are kept concise but clear.
  2. Consistent Syntax:

    • Used backticks for string interpolation where appropriate.
  3. Optional Chaining:

    • Simplified ternary expressions using optional chaining.

These changes make the code cleaner and more maintainable while still adhering to proper coding practices.

'OR'
),
problem_delete: () =>
hasPermission (
Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The code is mostly correct but there are some optimizations and improvements that can be made:

  • Combine the problem_read and problem_relate functions into one to avoid duplication.
  • Consider using named parameters for clarity.

Here's an optimized version of the code:

const share = {
  /**
   * Check if the current user has permission to read problems from shared knowledge.
   */
  problem_permission: (action) => {
    return hasPermission(
      action === 'read' ? ['RoleConst.ADMIN', PermissionConst.SHARED_KNOWLEDGE_PROBLEM_READ] : // Read operation requires admin or specific permission
      [RoleConst.ADMIN], // Delete operation only requires admin role
      'OR'
    );
  }
};

Optimizations Made:

  1. Function Combination: The problem_read and problem_relate functions have been combined into a single function called problem_permission, which takes an additional parameter action, indicating whether it's a read or delete operation.
  2. Named Parameters: Used action instead of hardcoding strings for readability and maintainability.

This approach makes the code more concise and easier to understand. Additionally, it provides a clear structure for handling different permissions based on actions (read, delete).

),
problem_create: (source_id:string) =>
hasPermission(
[
Copy link
Copy Markdown
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 potential issues and optimizations that can be made to improve the provided code:

  1. Redundant Permissions: The problem_read method checks both a specific resource permission and a generic "workspace manage" role. While this might seem redundant, it could be improved if you want to ensure consistency in how permissions are being checked.

  2. Complexity of Permission Logic: The use of multiple roles and complex logic within the hasPermission function makes it harder to understand and maintain. Consider simplifying the permission logic where possible.

  3. Consistent Error Handling: The return value from some methods (problem_edit, etc.) assumes false. It's unclear what these functions should do when no permission is granted. Consistently handling errors would make the code more robust.

  4. Security Concerns: Ensure that all permissions are correctly defined and enforced at each layer of your application.

Here's a potentially optimized version of the code with some recommendations applied:

const workspace = {
    // Simplified read permission logic
    problem_read: (source_id) =>
        hasPermission([
            RoleConst.WORKSPACE_MANAGE.getWorkspaceRole,
            PermissionConst.KNOWLEDGE_PROBLEM_READ.getKnowledgeWorkspaceResourcePermission(source_id)
        ], 'AND'),

    // Assuming same pattern applies to other CRUD operations
    problem_create: (source_id) =>
        hasPermission([
            RoleConst.WORKSPACE_MANAGE.getWorkspaceRole,
            PermissionConst.KNOWLEDGE_PROBLEM_CREATE.getKnowledgeWorkspaceResourcePermission(source_id)
        ], 'AND'),
    
    // Continue similar patterns for edit, delete as needed

    // Optional: Add helper methods or enums for easier management of constants
}

// Example usage with placeholder functions for hasPermission and related constants
function hasPermission(permissions, condition) {
    // Implementation details here
    switch (condition) {
        case 'AND':
            return permissions.every(checker);
        case 'OR':
            return permissions.some(checker);
        default:
            throw new Error('Invalid condition');
    }

    function checker(permission) {
        // Placeholder implementation here
        console.log(`Checking permission: ${permission}`);
        return true; // Return false if access not allowed
    }
}

In this revised approach:

  • The problem_read function now directly checks against the necessary roles and knowledge-specific permissions, making the logic simpler.
  • A generic hasPermission function handles checking combinations of permissions based on the desired condition ('AND' or 'OR').
  • Additional helper mechanisms like a checker function inside hasPermission can be used for detailed logging or different types of checks if required.

These changes aim to improve readability, reduce redundancy, enhance security, and prepare the base for further optimizations or improvements.

@zhanweizhang7 zhanweizhang7 merged commit 1febd0a into v2 Aug 5, 2025
3 of 5 checks passed
@zhanweizhang7 zhanweizhang7 deleted the pr@v2@fix_problem_read_permission branch August 5, 2025 03:49
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