antdPro 权限管理(1)

1,168 阅读2分钟

「这是我参与11月更文挑战的第2天,活动详情查看:2021最后一次更文挑战」。

在项目里面不一样的使用场景,有不一样的用户权限也不一样。比如:

  • 不一样的用户在页面种能看到的元素和操作不一样
  • 不一样的用户对于页面的访问权限不一样

在antdPro 中提供了一种简单易用的解决方案。是居于@umi/plugin-access插件实现的。

实现方式。

首先创建src/access.js文件

export default function access(initialState) {
  const { currentUser,hasRoutes,role} = initialState || {};
  return {
    canAdmin: currentUser && currentUser.access === 'admin', //定义用户类型
    normalRouteFilter: (route) => { //用以判断用户是否拥有路由权限
      
      return hasRoutes.includes(route.path)
    },
    canRead:(porps)=>{  //用以判断用户是否有页面内的某权限
      return role[porps.route.name].includes('read')
    }
  };
}

该文件返回一个function,返回的function 会在应用初始化阶段被执行。执行后返回的对象的每个key对应一个布尔值(boolean),代表用户是否拥有该权限。

在src/app.jsx 中 getInitialState() 函数中添加

    const hasRoutes = ['/dashboard/workplace','/from','/form/basic-form']
    const role = {
        'advanced-form':['rea','re']
    }
    const currentUser = {
      'access':'admin'
    }
    
    return {
      currentUser,
      hasRoutes,
      role,
    }
    

角色权限

canAdmin 用以判断,currentUser.access 是否等于 'admin',返回一个布尔值(boolean)

需要在路由中添加 access: 'canAdmin' 如:

    {
      name: 'monitor',
      icon: 'smile',
      path: '/dashboard/monitor',
      component: './dashboard/monitor',
      access: 'canAdmin'
    },

路由权限

canRead 传入路由。用以判断,hasRoutes 这个数组中是否有该路由。返回一个布尔值(boolean)

需要在路由中添加 access: 'canAdmin' 如:

    {
      name: 'workplace',
      icon: 'smile',
      path: '/dashboard/workplace',
      component: './dashboard/workplace',
      access: 'normalRouteFilter'
    },

页面内权限

canRead 传入props。用以判断,role 这个对象中是否有,以当前路由参数名为参数,的数组中是否有该权限参数。返回一个布尔值(boolean)

页面内实现 src/pages/form/advanced-form/index.jsx 如:

首先页面内引入useAccess, Access
import { useAccess, Access } from 'umi';

const access = useAccess()

//该函数可以获取到 src/access.js重定义的所有对象

  <Access
    accessible={access.canRead(props)} //调用access.canRead方法传入props 用以判断权限
    fallback={<div>Can not read foo content.</div>}
  >
    Foo content.
  </Access>

Access组件用以显示和隐藏元素

  • accessible 用以判断是否有权限。
  • fallback 用以无权限是提示内容