Skip to content
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

feat: 路由增加perms配置项 #4706

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

menglidong
Copy link

@menglidong menglidong commented Oct 21, 2024

Description

路由增加perms配置项
其和authority区别:

  • perms使用accessCodes权限码数据
  • authority使用的是roles角色编码数据

Type of change

Please delete options that are not relevant.

  • New feature (non-breaking change which adds functionality)

Checklist

ℹ️ Check all checkboxes - this will indicate that you have done everything in accordance with the rules in CONTRIBUTING.

  • If you introduce new functionality, document it. You can run documentation with pnpm run docs:dev command.
  • Run the tests with pnpm test.
  • Changes in changelog are generated from PR name. Please, make sure that it explains your changes in an understandable manner. Please, prefix changeset messages with feat:, fix:, perf:, docs:, or chore:.
  • My code follows the style guidelines of this project
  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes
  • Any dependent changes have been merged and published in downstream modules

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced access control by incorporating user-specific access codes in route generation, allowing for more granular permission management.
    • Added new properties for permissions in route metadata to facilitate better access management.
  • Bug Fixes

    • Improved logic for route accessibility checks based on user roles and permissions.
  • Documentation

    • Updated typings to reflect new properties for managing access codes and permissions in routing interfaces.

These changes aim to improve user experience by ensuring that access to routes is more accurately tailored to individual user permissions.

Copy link

changeset-bot bot commented Oct 21, 2024

⚠️ No Changeset found

Latest commit: 52be26b

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

Copy link
Contributor

coderabbitai bot commented Oct 21, 2024

Walkthrough

The changes in this pull request involve modifications to the setupAccessGuard function across multiple router guard files, where a new parameter, accessCodes, is introduced to enhance access control logic. This parameter is passed to the generateAccess function, allowing for more granular management of user permissions based on their access codes. Additionally, updates are made to several TypeScript interfaces to include optional properties for managing permissions and access codes, ultimately refining the route generation process and access checks within the application.

Changes

File Path Change Summary
apps/web-antd/src/router/guard.ts Updated setupAccessGuard to include accessCodes in generateAccess function call.
apps/web-ele/src/router/guard.ts Updated setupAccessGuard to include accessCodes in generateAccess function call.
apps/web-naive/src/router/guard.ts Updated setupAccessGuard to include accessCodes in generateAccess function call.
packages/@core/base/typings/src/vue-router.d.ts Added perms?: string[] to RouteMeta and accessCodes?: string[] to GenerateMenuAndRoutesOptions.
packages/effects/access/src/accessible.ts Updated generateRoutes to include accessCodes in options parameter destructuring.
packages/utils/src/helpers/generate-routes-frontend.ts Updated generateRoutesByFrontend to include accessCodes and added hasPerms function for access checks.

Possibly related PRs

  • perf: 优化 router/guard.ts  #4402: The changes in this PR involve modifications to the setupAccessGuard function in both apps/web-antd/src/router/guard.ts and apps/web-ele/src/router/guard.ts, which include the addition of the accessCodes parameter to the generateAccess function, directly relating to the access control logic enhanced in the main PR.

Suggested reviewers

  • anncwb
  • vince292007

Poem

In the garden where codes align,
Access granted, all is fine.
With roles and permissions in a dance,
Granular control gives us a chance.
Hopping through routes, we find our way,
A secure path for every day! 🐇✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Outside diff range and nitpick comments (7)
packages/effects/access/src/accessible.ts (2)

45-45: LGTM! Consider adding a type annotation for clarity.

The addition of accessCodes to the generateRoutes function aligns well with the PR objectives. The implementation looks correct and maintains backward compatibility.

For improved clarity, consider adding a type annotation for accessCodes:

- const { forbiddenComponent, roles, routes, accessCodes } = options;
+ const { forbiddenComponent, roles, routes, accessCodes }: { accessCodes?: string[] } = options;

This change would make the expected type of accessCodes more explicit.

Also applies to: 57-57


Missing accessCodes in GenerateMenuAndRoutesOptions type

The accessCodes property is not included in the GenerateMenuAndRoutesOptions type. This omission can lead to TypeScript errors and potential runtime issues.

  • File: @vben/types - Add accessCodes to GenerateMenuAndRoutesOptions.
🔗 Analysis chain

Line range hint 1-87: Verify completeness of accessCodes implementation

The changes to add accessCodes are well-implemented in the generateRoutes function. However, to ensure full support for this new functionality:

  1. Check if the GenerateMenuAndRoutesOptions type (imported from @vben/types) has been updated to include the accessCodes property.
  2. Verify if the generateAccessible function needs to handle accessCodes in any way.

Run the following script to check these:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the implementation of accessCodes across related files

# Test 1: Check if GenerateMenuAndRoutesOptions includes accessCodes
echo "Checking GenerateMenuAndRoutesOptions definition:"
rg -A 5 "type GenerateMenuAndRoutesOptions" 

# Test 2: Check if generateAccessible function handles accessCodes
echo "Checking generateAccessible function:"
rg -A 10 "function generateAccessible"

# Test 3: Check for any other occurrences of accessCodes
echo "Checking for other occurrences of accessCodes:"
rg "accessCodes"

Length of output: 3292

apps/web-naive/src/router/guard.ts (1)

104-104: LGTM! Consider adding a comment for clarity.

The addition of accessCodes to the generateAccess function call enhances the access control logic by incorporating user-specific access codes. This change aligns well with the PR objectives and is consistent with similar modifications in other parts of the codebase.

Consider adding a brief comment explaining the purpose of accessCodes for better code readability:

 const { accessibleMenus, accessibleRoutes } = await generateAccess({
+  // Include user-specific access codes for granular permission control
   accessCodes: accessStore.accessCodes || [],
   roles: userRoles,
   router,
   // 则会在菜单中显示,但是访问会被重定向到403
   routes: dynamicRoutes,
 });
apps/web-antd/src/router/guard.ts (1)

105-105: LGTM! Consider adding a comment for clarity.

The addition of accessCodes to the generateAccess function call is a good implementation of the new perms configuration for routing. It enhances access control by incorporating user-specific access codes while maintaining backward compatibility.

Consider adding a brief comment explaining the purpose of accessCodes for better code readability:

 const { accessibleMenus, accessibleRoutes } = await generateAccess({
+  // User-specific access codes for granular permission control
   accessCodes: accessStore.accessCodes || [],
   roles: userRoles,
   router,
   // 则会在菜单中显示,但是访问会被重定向到403
   routes: dynamicRoutes,
 });
apps/web-ele/src/router/guard.ts (1)

105-108: LGTM! Consider adding a comment for clarity.

The addition of accessCodes to the generateAccess function call aligns well with the PR objectives to introduce a new perms configuration for routing. This change allows for more granular control over user permissions based on access codes.

Consider adding a brief comment explaining the purpose of the accessCodes parameter for better code readability:

 const { accessibleMenus, accessibleRoutes } = await generateAccess({
+  // Use access codes for granular permission control
   accessCodes: accessStore.accessCodes || [],
   roles: userRoles,
   router,
   // 则会在菜单中显示,但是访问会被重定向到403
   routes: dynamicRoutes,
 });
packages/utils/src/helpers/generate-routes-frontend.ts (2)

49-53: Update the documentation for hasPerms function

The comments for the hasPerms function are currently identical to those of hasAuthority. Please update the comments to accurately describe the purpose and parameters of hasPerms, ensuring clarity for future maintainers.


54-62: Enhance parameter naming for clarity and consistency

In the hasPerms function, consider renaming the parameter access to accessCodes to clearly indicate that it represents access codes. This aligns with the parameter naming in generateRoutesByFrontend and improves code readability.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 1b172b0 and 52be26b.

📒 Files selected for processing (6)
  • apps/web-antd/src/router/guard.ts (1 hunks)
  • apps/web-ele/src/router/guard.ts (1 hunks)
  • apps/web-naive/src/router/guard.ts (1 hunks)
  • packages/@core/base/typings/src/vue-router.d.ts (2 hunks)
  • packages/effects/access/src/accessible.ts (2 hunks)
  • packages/utils/src/helpers/generate-routes-frontend.ts (2 hunks)
🧰 Additional context used
🔇 Additional comments (2)
packages/@core/base/typings/src/vue-router.d.ts (2)

105-108: LGTM: New perms property aligns with PR objectives

The addition of the perms?: string[] property to the RouteMeta interface is consistent with the PR's goal of introducing a new configuration option for routing. This optional property allows for specifying permission codes required for access, enhancing the granularity of access control in the routing system.


128-128: LGTM: New accessCodes property complements the perms addition

The introduction of the accessCodes?: string[] property in the GenerateMenuAndRoutesOptions interface is a logical complement to the perms property. This optional property allows for passing access codes when generating menus and routes, which aligns with the PR's objective of utilizing accessCodes for permission data in the routing system.

Comment on lines +16 to +17
if (!route.meta?.authority) {
return hasPerms(route, accessCodes);
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider refactoring to reduce code duplication between hasAuthority and hasPerms

The functions hasAuthority and hasPerms share similar logic for access checks based on route metadata. To improve maintainability and reduce redundancy, consider refactoring these functions to share common code or merging them if appropriate.

@@ -8,10 +8,14 @@ import { filterTree, mapTree } from '@vben-core/shared/utils';
async function generateRoutesByFrontend(
routes: RouteRecordRaw[],
roles: string[],
accessCodes: string[],
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Missing accessCodes Parameter in generateRoutesByFrontend Invocations

  • packages/utils/src/helpers/__tests__/generate-routes-frontend.test.ts: Several test cases are missing the accessCodes parameter.
  • packages/effects/access/src/accessible.ts: Invocation of generateRoutesByFrontend does not include accessCodes.
🔗 Analysis chain

Ensure all invocations of generateRoutesByFrontend include the new accessCodes parameter

The addition of the accessCodes parameter to the generateRoutesByFrontend function requires updating all places where this function is called. Please verify that all invocations pass the appropriate accessCodes to prevent potential runtime errors.

To assist with this verification, you can run the following script to locate all calls to generateRoutesByFrontend:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all invocations of `generateRoutesByFrontend` and check for the `accessCodes` parameter.

# Search for the function calls to `generateRoutesByFrontend`
rg -A 2 -B 2 'generateRoutesByFrontend\(' --glob '!packages/utils/src/helpers/generate-routes-frontend.ts'

Length of output: 2104

@deivisonrpg
Copy link

It would be great to have this option; sometimes, just role-based permissions are not enough

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