CheckPermissions.tsx 2.3 KB

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