CheckPermissions.jsx 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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 (currentAuthority instanceof Promise) {
  20. return currentAuthority.then(Authority => {
  21. if (Authority.some(item => authority.includes(item))) {
  22. return target
  23. }
  24. return Exception
  25. })
  26. }
  27. if (Array.isArray(currentAuthority)) {
  28. if (currentAuthority.some(item => authority.includes(item))) {
  29. return target
  30. }
  31. } else if (authority.includes(currentAuthority)) {
  32. return target
  33. }
  34. return Exception
  35. } // string 处理
  36. if (typeof authority === 'string') {
  37. if (Array.isArray(currentAuthority)) {
  38. if (currentAuthority.some(item => authority === item)) {
  39. return target
  40. }
  41. } else if (authority === currentAuthority) {
  42. return target
  43. }
  44. return Exception
  45. } // Promise 处理
  46. if (authority instanceof Promise) {
  47. return <PromiseRender ok={target} error={Exception} promise={authority} />
  48. } // Function 处理
  49. if (typeof authority === 'function') {
  50. const bool = authority(currentAuthority) // 函数执行后返回值是 Promise
  51. if (bool instanceof Promise) {
  52. return <PromiseRender ok={target} error={Exception} promise={bool} />
  53. }
  54. if (bool) {
  55. return target
  56. }
  57. return Exception
  58. }
  59. throw new Error('unsupported parameters')
  60. }
  61. export { checkPermissions }
  62. function check(authority, target, Exception) {
  63. return checkPermissions(authority, CURRENT, target, Exception)
  64. }
  65. export default check