Skip to content

feat: Resource application permission #3787

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 31, 2025

Conversation

shaohuzhang1
Copy link
Contributor

feat: Resource application permission

Copy link

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

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.

Copy link

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

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

) {
return `/application/resource-management/${item.id}/${item.type}/chat-log`
} else return `/system/resource-management/application/`
}

const workspaceOptions = ref<any[]>([])
const workspaceVisible = ref(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.

In this code snippet, there are several improvements can be made:

  1. Use v-show Instead of v-if:

    <el-tooltip
      v-show="... condition ... "
      :effect="..."
      
      ...
    
      <!-- Use v-show instead of v-if -->
      <el-button text v-show="morefilledper()"  
        @click="
          router.push({
            path: `/application/resource-management/${row.id}/${row.type}/overview`,
          })
        "
      >
        
        ...
        
      </el-button>
    
      ...
     
     
      
    
    
      
      
      
      
      <div v-show="otherCondition">
           ...
      </div>   
    
  2. Code Optimization:

    • The use of conditional rendering in Vue components might make the code longer than strictly necessary. For example, you could extract parts of logic into functions rather than writing it inline where possible.
    <template>
      <!-- Code using v-show with multiple conditions can be condensed -->
      <Tooltip
        v-for="(cond, key) in conditionsObj" 
         v-show="!cond.condition" 
        :key="key"
        :effect="tooltipEffect"
        placement="top"   
        > 
        
        ......
        
        
      </Tooltip>
    
    </template>
    
    <script lang="ts">
    
      export default {
       setup(){
         const conditonsObj = {
            condblockA:{
             condition:true,
                // Other data...
             },
            condblockB:{
                condition:false,
               
               
                 
              
                //Other data
              },
            
            // other similar objects
        
           
         }
    
         const showComp = (obj)=>{
              return !data.some(el=> el === obj)
             
          }
    
    
         
         
         const tooltipEffect='dark';
    
       
       
      
    
    
         return{conditionsObj,showComp}
        }
      }
    </script>
    

3. **Consistent Code Styling:**
    - It's important to ensure consistent styling across your HTML and JavaScript code for readability.
    ```
    <!-- CSS style guide examples -->

    .element-class-name {
        color: blue;
        font-size: 14px;
        line-height: 24px; /* Optional but recommended */
        background-color: lightgray;
        padding: 5px;
        border-radius: 4px;
     }

     div.container{
        max-width: 80%;
        margin: auto;
     }
    ```

**Note:** I've provided general suggestions that will help improve the efficiency and maintainability of your Vue.js application without changing any existing functionality. Adjust them according to specific project requirements or additional context. Let me know if more details on specific aspects of your implementation are needed!

()=>{
const to: any = get_next_route()
if (to.path.includes('resource-management')) { return PermissionConst.RESOURCE_APPLICATION_CHAT_LOG_READ}
},
]
},
component: () => import('@/views/chat-log/index.vue'),
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 code snippet is an implementation of Vue Router routes with permission checks on resource-based access. Here's a breakdown of some suggestions and potential improvements:

  1. Avoid Redundant Calls: The code calls get_next_route() multiple times without storing the result. Consider caching this value or reusing it.

  2. Optimize Permissions Check:

    • Consolidate the logic for determining who gets what permissions based on route path.
    • Use a more dynamic approach to determine which permissions should be allowed when accessing certain sections of the application.
  3. Use Caching Mechanisms: Cache the route parameters to avoid recalculating them unnecessarily during navigation changes.

  4. Code Duplication: Notice that similar logic appears several times (ADMIN, read-write, etc.). Refactor common parts into helper functions.

  5. Logging Improvements: Move the logging statement inside where its meaningful (in the case where permissions are granted).

Here's an improved version incorporating these suggestions:

const ApplicationDetailRouter = [
  {
    path: '/application/:id/overview',
    meta: {
      permissionCheckers: (to) => {
        const hasResourceManagementPath =
          // Implement logic here to determine if there is a specific path related to Resource Management
          false; // Replace with actual logic

        return [
          () =>
            !hasResourceManagementPath ||
            PermissionConst.APPLICATION_OVERVIEW_READ.getApplicationWorkspaceResourcePermission(to?.params.id),
          () => (!hasResourceManagementPath || RoleConst.ADMIN),
          () =>
            !hasResourceManagementPath ||
            PermissionConst.RESOURCE_APPLICATION_OVERVIEW_READ,
        ];
      },
    },
    component: () => import('@/views/application-overview/index.vue'),
  },
  {
    path: '/application/:id/edit',
    meta: {
      permissionCheckers: (to) => {
        const hasResourceManagementPath =
          // Implement logic here to determine if there is a specific path related to Resource Management
          false;

        return [
          () => !hasResourceManagementPath ||
                  PermissionConst.APPLICATION_EDIT.getApplicationWorkspaceResourcePermission(to?.params.id),
          () => (!hasResourceManagementPath || RoleConst.ADMIN),
          () =>
            !hasResourceManagementPath ||
            PermissionConst.RESOURCE_APPLICATION_EDIT,
        ];
      },
    },
    component: () => import('@/views/application/ApplicationSetting.vue'),
  },
  {
    // Rest of the routes remain unchanged but apply the same logic through their respective meta.permissionsChecker
  }
];

Note: The above suggestion assumes you have a specific way to identify paths associated with "Resource Management." Adjust the logic accordingly based on your application structure.

By addressing redundant function calls and consolidating duplicate logic, we can make the code cleaner and potentially enhance performance, given the complexity involved in routing and security checks within applications.

@zhanweizhang7 zhanweizhang7 merged commit 356229c into v2 Jul 31, 2025
3 of 5 checks passed
@zhanweizhang7 zhanweizhang7 deleted the pr@v2@feat_resource_application_permission branch July 31, 2025 06:43
RoleConst.ADMIN,
PermissionConst.RESOURCE_APPLICATION_CHAT_LOG_READ
],
'OR')
}
export default systemManage
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 code snippet is a simplified representation of defining permission management logic within a system interface using Role-based Access Control (RBAC). You've highlighted several potential improvements:

Potential Issues/Improvements:

  1. Code Duplicity: The methods overview_read, access_read, chat_user_read, and chat_log_read essentially repeat similar logic with only slight variations. This can lead to redundancy and maintenance challenges.

  2. Repetition of Role Check: There appears to be repetition in hardcoding roles like RoleConst.ADMIN. Consider storing these constants elsewhere to prevent duplication and make changes easily if needed.

  3. Variable Initialization: Although it's minimal in this case, initializing variables at the top can sometimes clean up the function body and make it more readable.

  4. Method Naming: While descriptive, some method names (overview_read, access_read) may not clearly convey their functionality. Consider renaming them to better reflect the operations they perform.

  5. Function Arguments: Currently, all functions take an array of permissions as their third argument, which could benefit from being documented or made consistent across all implementations.

  6. Return Type Expectation: Ensure that each function returns a boolean indicating whether the user has read access based on the role(s) specified.

Here’s an optimized version of the code with some suggestions applied:

const { RoleConst, PermissionConst } = require('path-to-your-permissions-module'); // Adjust path accordingly

// Helper function to determine permission status
function hasPermissions(userRoles, requiredPermissions, type = 'OR') {
  return userRoles.some(role => {
    const matchingPermissions = requiredPermissions.filter(permission =>
      typeof permission === 'string' ? permission.includes(role) : Array.isArray(permission) && permission.includes(role)
    );
    switch (type.toUpperCase()) {
      case 'AND':
        return matchingPermissions.length === requiredPermissions.length;
      case 'OR':
        return matchingPermissions.length > 0;
      default:
        throw new Error(`Unsupported type: ${type}`);
    }
  });
}

/**
 * Manages different types of application data read accesses.
 */
const systemManage = {
  overview_read: () => hasPermissions(
    [ RoleConst.ADMIN ],
    [ PermissionConst.RESOURCE_APPLICATION_OVERVIEW_READ ]
  ),
  
  access_read: () => hasPermissions(
    [ RoleConst.ADMIN ],
    [ PermissionConst.RESOURCE_APPLICATION_ACCESS_READ ]
  ),

  chat_user_read: () => hasPermissions(
    [ RoleConst.ADMIN ],
    [ PermissionConst.RESOURCE_APPLICATION_CHAT_USER_READ ]
  ),  
  
  chat_log_read: () => hasPermissions(
    [ RoleConst.ADMIN ],
    [ PermissionConst.RESOURCE_APPLICATION_CHAT_LOG_READ ]
  ) 
};

export default systemManage;

Key Improvements:

  • Helper Function: A reusable helper function hasPermissions encapsulates the role-checking logic, making it easier to modify the logic for checking multiple conditions in one place.
  • DRY Principle: By reusing the same logic across multiple methods, we reduce code duplication.
  • Comments/documentation: Added comments to describe the purpose of each function.
  • Consistent Structure: Ensured that the structure remains clear and understandable.

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