CheckPermissions.jsx 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import React from 'react'
  2. import { CURRENT } from './renderAuthorize' // eslint-disable-next-line import/no-cycle
  3. import PromiseRender from './PromiseRender'
  4. /**
  5. * 通用权限检查方法
  6. * Common check permissions method
  7. * @param { 权限判定 | Permission judgment } authority
  8. * @param { 你的权限 | Your permission description } currentAuthority
  9. * @param { 通过的组件 | Passing components } target
  10. * @param { 未通过的组件 | no pass components } Exception
  11. */
  12. const checkPermissions = (authority, currentAuthority, target, Exception) => {
  13. // 没有判定权限.默认查看所有
  14. // Retirement authority, return target;
  15. if (!authority) {
  16. return target
  17. } // 数组处理
  18. if (Array.isArray(authority)) {
  19. if (Array.isArray(currentAuthority)) {
  20. if (currentAuthority.some((item) => authority.includes(item))) {
  21. return target
  22. }
  23. } else if (authority.includes(currentAuthority)) {
  24. return target
  25. }
  26. return Exception
  27. } // string 处理
  28. if (typeof authority === 'string') {
  29. if (Array.isArray(currentAuthority)) {
  30. if (currentAuthority.some((item) => authority === item)) {
  31. return target
  32. }
  33. } else if (authority === currentAuthority) {
  34. return target
  35. }
  36. return Exception
  37. } // Promise 处理
  38. if (authority instanceof Promise) {
  39. return <PromiseRender ok={target} error={Exception} promise={authority} />
  40. } // Function 处理
  41. if (typeof authority === 'function') {
  42. const bool = authority(currentAuthority) // 函数执行后返回值是 Promise
  43. if (bool instanceof Promise) {
  44. return <PromiseRender ok={target} error={Exception} promise={bool} />
  45. }
  46. if (bool) {
  47. return target
  48. }
  49. return Exception
  50. }
  51. throw new Error('unsupported parameters')
  52. }
  53. export { checkPermissions }
  54. function check(authority, target, Exception) {
  55. return checkPermissions(authority, CURRENT, target, Exception)
  56. }
  57. export default check