“This is the second day of my participation in the November Gwen Challenge. See details of the event: The last Gwen Challenge 2021”.
Different use scenarios in the project, there are different user permissions are not the same. Such as:
- Different users can see different elements and actions on the page
- Different users have different access rights to the page
An easy-to-use solution is provided in antdPro. It is implemented by the @umi/plugin-access plugin.
Implementation mode.
Start by creating the SRC /access.js file
export default function access(initialState) {
const { currentUser,hasRoutes,role} = initialState || {};
return {
canAdmin: currentUser && currentUser.access === 'admin'.// Define the user type
normalRouteFilter: (route) = > { // To check whether the user has the route permission
return hasRoutes.includes(route.path)
},
canRead:(porps) = >{ // It is used to determine whether a user has permissions on the page
return role[porps.route.name].includes('read')}}; }Copy the code
This file returns a function that will be executed during application initialization. Each key of the object returned after execution corresponds to a Boolean value indicating whether the user has the permission.
Add it to the getInitialState () function in SRC /app.jsx
const hasRoutes = ['/dashboard/workplace'.'/from'.'/form/basic-form']
const role = {
'advanced-form': ['rea'.'re']}const currentUser = {
'access':'admin'
}
return {
currentUser,
hasRoutes,
role,
}
Copy the code
Role authorization
CanAdmin: currentUser.access = ‘admin’ and returns a Boolean
Need to add access to route: ‘canAdmin’ for example:
{
name: 'monitor'.icon: 'smile'.path: '/dashboard/monitor'.component: './dashboard/monitor'.access: 'canAdmin'
},
Copy the code
Routing permissions
CanRead Incoming route. To determine whether the route exists in the hasRoutes array. Return a Boolean value (Boolean)
Need to add access to route: ‘canAdmin’ for example:
{
name: 'workplace'.icon: 'smile'.path: '/dashboard/workplace'.component: './dashboard/workplace'.access: 'normalRouteFilter'
},
Copy the code
In-page permissions
CanRead is passed to props. To determine whether the role object contains the permission parameter in the array named parameters of the current route. Return a Boolean value (Boolean)
SRC /pages/form/advanced-form/index.jsx
First introduce useAccess, Accessimport { useAccess, Access } from 'umi';
const access = useAccess()
// This function gets all objects redefined by SRC /access.js
<Access
accessible={access.canRead(props)} // Call the access.canRead method to props to determine the permission
fallback={<div>Can not read foo content.</div>}
>
Foo content.
</Access>
Copy the code
The Access component is used to show and hide elements
- Accessible Indicates whether a permission is granted.
- Fallback is used to prompt content without permission