凌晨被难哭的权限管理竟如此简单

前言碎碎念

刚接手React项目,遇到一个需求要根据用户角色展示不同的页面,由于对react不是很熟悉,导致下了班还在查文档,项目里用到了@umijs/plugin-access。

@umijs/plugin-access 是一个 Umi 插件,用于根据用户角色来展示不同的页面。它提供了一种简便的方式来控制页面的访问权限。

实现

  1. 登陆之后用useModel手动设置 initialState 的值
import {useModel} from 'umi';
const {initialState, setInitialState} = useModel('@@initialState');

//登陆之后拿到userInfo
await fetchUserInfo(userInfo);

const fetchUserInfo = async (value) => {
    if (value) {
      await setInitialState((s) => ({...s, currentUser: value}));
    }

};
  1. 项目中的src目录下创建access.ts文件
/**
 * @see https://umijs.org/zh-CN/plugins/plugin-access
 * */
// 角色Id为17是超级管理员,18为管理员,其余为普通用户
export default function access(initialState: { currentUser?: API.CurrentUser | undefined }) {
  const {currentUser} = initialState || {};

  return {
    login: currentUser !== undefined,
    canAccess: currentUser ? currentUser.roleId == '17' || currentUser.roleId == '18' : undefined,
    canAdminAccess: currentUser ? currentUser.roleId == '17' : undefined,

  }
}

3在你的路由配置文件中,你可以通过设置 access 属性来控制页面的访问权限。例如:

import access from '@/access';

export default [
  {
    path: '/home',
    component: '@/pages/index',
  },
  {
    name: '系统管理',
    path: '/systemManage',
    component: './SystemManage',
    authority: ['admin'],
    access: 'canAccess',
    routes: [
      {
        name: '数据管理',
        path: './data',
        component: './SystemManage/dataManage',
      },
      {
        name: '用户管理',
        path: './user',
        component: './SystemManage/userManage',
        access: 'canAdminAccess'
      }
    ],
  },
  // 其他路由配置...
];
 

这样就可以根据用户角色来展示不同的页面了。当用户的角色为 管理员 时,可以访问设置了 access: ‘canAccess’ 属性的页面;当用户的角色为 超级管理员 时,可以访问设置了 access: ‘canAdminAccess’ 属性的页面,否则访问受限。

  • 13
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值