access.ts 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // src/access.ts
  2. export default function access(initialState: { currentUser?: API.CurrentUser | undefined, menu?: any }) {
  3. const { currentUser, menu } = initialState || {};
  4. let obj = {}
  5. let bdObj = {}
  6. /**
  7. * 因为pro不让动态修改路由只能动态获取菜单
  8. * 逻辑用户登录信息的access角色标识,对服务器菜单menu进行遍历,对比roles角色中是否存在access,无为没权限
  9. * 最后以path名为key以判断布尔值为value返回对象集合
  10. * 再在本地config的routes中对应菜单配置access管控菜单权限值为这里返回对应的key
  11. * 做到这一步只能阻止强行输入路径返回无权限页面无法隐藏没有权限的菜单
  12. * 需要在app中menuDataRender的时候对应数据进行再次处理判断进行隐藏
  13. */
  14. function btnMap(btns: any) {//按钮级权限
  15. btns?.map((btn:any)=>{
  16. Object.keys(btn).forEach((key: string) => {
  17. if(key === 'name'){
  18. obj[btn[key]] = true
  19. }
  20. })
  21. })
  22. }
  23. function btnMaps(btns: any) {//按钮级权限
  24. btns?.map((btn:any)=>{
  25. Object.keys(btn).forEach((key: string) => {
  26. if(key === 'name'){
  27. obj[btn[key]] = true
  28. }
  29. })
  30. })
  31. }
  32. function nameMap(menu: any[]) {//路由权限
  33. menu?.forEach((item: any) => {
  34. let arr = item?.path?.split('/')//分割path路径为数组
  35. if (Array.isArray(arr)) {
  36. obj[arr[arr?.length - 1]] = item?.roles?.indexOf(currentUser?.access) !== -1 //将路径的最后一个字段作为权限名称,值为查找当前路由的roles的值是否存在个人信息权限中,不存在就是false不展示
  37. }
  38. if (item.routes) {//假如item有子路由重新执行函数
  39. nameMap(item.routes)
  40. }
  41. if (item?.routes?.length >0 && !item?.routes[0].path) {//假如item有按钮路由执行按钮权限判断
  42. btnMap(item.routes)
  43. }
  44. })
  45. }
  46. function nameMaps(menu: any[]) {//路由权限
  47. menu?.forEach((item: any) => {
  48. let arr = item?.path?.split('/')//分割path路径为数组
  49. if (Array.isArray(arr)) {
  50. bdObj[arr[arr.length - 1]] = ['admin'].indexOf(currentUser?.access) !== -1
  51. }
  52. if (item.routes) {
  53. nameMaps(item.routes)
  54. }
  55. if (item?.routes?.length >0 && !item?.routes[0].path) {//假如item有按钮路由执行按钮权限判断
  56. btnMaps(item.routes)
  57. }
  58. })
  59. }
  60. if (menu) {
  61. nameMap(menu.data)//后端菜单列表
  62. }
  63. return { ...bdObj, ...obj };//合并本地和线上菜单,因为线上菜单不返回隐藏的菜单,所以需要本地全部菜单合并线上菜单才能正常控制前端权限,pro路由逻辑需要
  64. }