Skip to content

Conversation

@shaohuzhang1
Copy link
Contributor

feat: Resource permission in system-manage

@f2c-ci-robot
Copy link

f2c-ci-robot bot commented Jul 29, 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 Jul 29, 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

@zhanweizhang7 zhanweizhang7 merged commit b3fa1e5 into v2 Jul 29, 2025
3 of 4 checks passed
@zhanweizhang7 zhanweizhang7 deleted the pr@v2@feat_resource_permission_in_system_manage branch July 29, 2025 07:59
),

folderCreate: () => false,
folderEdit: () => false,
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 looks well-designed overall but can be optimized in several ways:

  1. Use of Arrays: The presence of multiple conditional checks for different functionalities can be consolidated into arrays, making it easier to manage and extend.

  2. Reusability: Create helper functions to handle permission logic consistently across different endpoints or features.

    function getPermissions(type) {
      return hasPermission([
        RoleConst.ADMIN,
        `RESOURCE_KNOWLEDGE_${type.toUpperCase()}` // Assuming type is like "chat"
      ],'OR');
    }
  3. Duplicated Code: Consider extracting common parts of each endpoint's permissions to improve maintainability.

  4. Documentation Commenting: Add detailed comments explaining the purpose of complex blocks or sections.

  5. Simplify Imports/Exports: If these methods are part of larger modules, ensure they don't unnecessarily import/export every time.

  6. Error Handling: Implement basic error handling if necessary when calling the hasPermission function.

Here’s an example of how you might refactor some of this:

const systemManage = {
  OR: (...args) => args.every(Boolean),
};

function hasPermission(neededRoles, joinTypeOrArray = 'OR') {
  let result;
  
  switch (joinTypeOrArray.toLowerCase()) {
    case 'and':
      result = neededRoles.every((role) => roleExists(role));
      break;
    default:
      result = neededRoles.some((role) => roleExists(role));
      break;
  }
  
  return result;
}

// Helper function to check if a role exists
function roleExists(roleName) {
  // Implementation depends on where roles are defined or loaded
  // Here we just assume it's available globally
  try {
    return global.roles.includes(roleName);
  } catch (err) {
    console.error("Error checking role existence:", err);
    return false;
  }
}

function initializePermissionsMap() {
  const permissionsMap = {};

  // Initialize specific permissions based on their types
  const permissionTypes = ['sync', 'vector', 'generate', 'edit', 'export', 'delete'];
  permissionTypes.forEach(type => {
    const key = `${type}_create`;
    permissionsMap[key] = (role) =>
      hasPermission([RoleConst.ADMIN, `RESOURCE_KNOWLEDGE_${key.split('_')[0].toUpperCase()}`]);
  });

  // Additional document-specific permissions...
  permissionsMap.doc_create = (role) =>
    hasPermission([RoleConst.ADMIN, PermissionConst.RESOURCE_KNOWLEDGE_DOCUMENT_CREATE]);

  permissionsMap.knowledge_chat_user_edit = (role) =>
    hasPermission([RoleConst.ADMIN, PermissionConst.RESOURCE_KNOWLEDGE_CHAT_USER_EDIT]);

  // Problem-related permissions...
  permissionsMap.problem_create = (role) =>
    hasPermission([RoleConst.ADMIN, PermissionConst.RESOURCE_KNOWLEDGE_PROBLEM_CREATE]);

  // Document-migration etc...

  // Return full map or individual objects as needed
  return permissionsMap;
}

This approach separates functionality into reusable components, which makes maintenance easier, and ensures that all similar permissions are handled similarly throughout the application.

],'OR'),

folderCreate: () => false,
folderEdit: () => false,
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 provided JavaScript function const systemManage contains several improvements to enhance readability, maintainability, and correctness:

  1. Separate Functions: Each action method should be defined independently within an object for better organization.

  2. Inline Permission Check: The permission checking logic can be extracted into a standalone function named hasPermission.

  3. Consistent Return Type: Ensure that all actions return either truthy or falsy values consistently.

Here's the improved version of the code:

const roleConst = {
  ADMIN: 'ADMIN',
};

const permissionConst = {
  RESOURCE_MODEL_EDIT: 'RESOURCE_MODEL_EDIT',
  RESOURCE_MODEL_DELETE: 'RESOURCE_MODEL DELETE',
};

function hasPermission(requiredRoles, operator) {
  if (operator === 'AND') {
    return requiredRoles.every(role => user.hasRole(role));
  } else if (operator === 'OR') {
    return requiredRoles.some(role => user.hasRole(role)); // Adjust depending on actual data structure
  }
}

const systemManage = {
  folderCreate: () => false,
  folderEdit: () => false,

  create: () =>
    hasPermission([roleConst.ADMIN], 'AND'),

  modify: () =>
    hasPermission([roleConst.ADMIN, permissionConst.RESOURCE_MODEL_EDIT], 'OR'),

  paramSetting: () =>
    hasPermission([roleConst.ADMIN, permissionConst.RESOURCE_MODEL_EDIT], 'OR'),

  delete: () =>
    hasPermission([roleConst.ADMIN, permissionConst.RESOURCE_MODEL_DELETE], 'OR'),
};

Key Improvements:

  • Modularization: Each action method is now separated into its own variable.

  • Function Extraction: Moved permission-checking logic inside the hasPermission function for clarity and reusability.

  • Consistency: All methods in the systemManage object use consistent naming conventions and types (false returns).

Ensure you have access to the necessary utility functions such as user.hasRole() in this context based on how your application manages roles and permissions.

import {PermissionConst, RoleConst} from '@/utils/permission/data'

const systemManage = {
create: () => false,
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 has several issues that need to be addressed:

  1. Removed Import Statement: The ComplexPermission type is required for permission checks but is removed from the import statement at line 3.

    To fix: Add back the import { ComplexPermission } from '@/utils/permission/type';

  2. Unused Function Call: There's a commented-out function call create => false within the systemManage object literal at lines 4-5. Since there aren't any other calls to this, you might want to remove it if not needed.

  3. Code Structure: While minor, consider organizing related functions or constants together rather than scattering them throughout the file.

Here’s the corrected version of your code with these suggested changes:

@@ -1,7 +1,8 @@
 import {hasPermission} from '@/utils/permission/index'
+import {ComplexPermission} from '@/utils/permission/type'

 const systemManage = {
     create() => false
 }

 // Add more functionalities here

 export default systemManage;

This should address the specified issues and improve the readability and functionality of your code.

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