Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions ui/src/permission/knowledge/system-share.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,14 +150,21 @@ const share = {
],
'OR'
),
problem_read: () => false,
problem_relate: () =>
problem_read: () =>
hasPermission (
[
RoleConst.ADMIN,
PermissionConst.SHARED_KNOWLEDGE_PROBLEM_READ
],
'OR'
),
problem_relate: () =>
hasPermission (
[
RoleConst.ADMIN,
PermissionConst.SHARED_KNOWLEDGE_PROBLEM_RELATE
],
'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).

Expand Down
11 changes: 10 additions & 1 deletion ui/src/permission/knowledge/workspace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,16 @@ const workspace = {
]
,'OR'
),
problem_read: () => false,
problem_read: (source_id:string) =>
hasPermission(
[
new ComplexPermission([RoleConst.USER],[PermissionConst.KNOWLEDGE.getKnowledgeWorkspaceResourcePermission(source_id)],[],'AND'),
RoleConst.WORKSPACE_MANAGE.getWorkspaceRole,
PermissionConst.KNOWLEDGE_PROBLEM_READ.getKnowledgeWorkspaceResourcePermission(source_id),
PermissionConst.KNOWLEDGE_PROBLEM_READ.getWorkspacePermissionWorkspaceManageRole,
],
'OR',
),
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.

Expand Down
1 change: 1 addition & 0 deletions ui/src/utils/permission/data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,7 @@ const PermissionConst = {
SHARED_KNOWLEDGE_PROBLEM_CREATE: new Permission('SYSTEM_KNOWLEDGE_PROBLEM:READ+CREATE'),
SHARED_KNOWLEDGE_PROBLEM_EDIT: new Permission('SYSTEM_KNOWLEDGE_PROBLEM:READ+EDIT'),
SHARED_KNOWLEDGE_PROBLEM_DELETE: new Permission('SYSTEM_KNOWLEDGE_PROBLEM:READ+DELETE'),
SHARED_KNOWLEDGE_PROBLEM_RELATE: new Permission('SYSTEM_KNOWLEDGE_PROBLEM:READ+RELATE'),

SHARED_KNOWLEDGE_HIT_TEST_READ: new Permission('SYSTEM_KNOWLEDGE_HIT_TEST:READ'),
KNOWLEDGE_HIT_TEST_READ: new Permission('KNOWLEDGE_HIT_TEST:READ'),
Expand Down
20 changes: 19 additions & 1 deletion ui/src/views/paragraph/component/ParagraphDialog.vue
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
<el-col :span="6" class="border-l" style="width: 300px">
<!-- 关联问题 -->
<ProblemComponent
v-if="permissionPrecise.problem_read(id)"
:paragraphId="paragraphId"
:docId="document_id"
:knowledgeId="id"
Expand All @@ -56,12 +57,14 @@
</el-dialog>
</template>
<script setup lang="ts">
import { ref, watch, nextTick } from 'vue'
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
Expand All @@ -73,6 +76,21 @@ const {
params: { id, documentId },
} = route as any

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

const permissionPrecise = computed(() => {
return permissionMap['knowledge'][apiType.value]
})


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.

Expand Down
Loading