动态菜单和动态路由的 antd pro

CheckPermissions.js 1.7KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import React from 'react';
  2. import PromiseRender from './PromiseRender';
  3. import { CURRENT } from './index';
  4. function isPromise(obj) {
  5. return (
  6. !!obj &&
  7. (typeof obj === 'object' || typeof obj === 'function') &&
  8. typeof obj.then === 'function'
  9. );
  10. }
  11. /**
  12. * 通用权限检查方法
  13. * Common check permissions method
  14. * @param { 权限判定 Permission judgment type string |array | Promise | Function } authority
  15. * @param { 你的权限 Your permission description type:string} currentAuthority
  16. * @param { 通过的组件 Passing components } target
  17. * @param { 未通过的组件 no pass components } Exception
  18. */
  19. const checkPermissions = (authority, currentAuthority, target, Exception) => {
  20. // 没有判定权限.默认查看所有
  21. // Retirement authority, return target;
  22. if (!authority) {
  23. return target;
  24. }
  25. // 数组处理
  26. if (Array.isArray(authority)) {
  27. if (authority.indexOf(currentAuthority) >= 0) {
  28. return target;
  29. }
  30. return Exception;
  31. }
  32. // string 处理
  33. if (typeof authority === 'string') {
  34. if (authority === currentAuthority) {
  35. return target;
  36. }
  37. return Exception;
  38. }
  39. // Promise 处理
  40. if (isPromise(authority)) {
  41. return <PromiseRender ok={target} error={Exception} promise={authority} />;
  42. }
  43. // Function 处理
  44. if (typeof authority === 'function') {
  45. try {
  46. const bool = authority(currentAuthority);
  47. if (bool) {
  48. return target;
  49. }
  50. return Exception;
  51. } catch (error) {
  52. throw error;
  53. }
  54. }
  55. throw new Error('unsupported parameters');
  56. };
  57. export { checkPermissions };
  58. const check = (authority, target, Exception) => {
  59. return checkPermissions(authority, CURRENT, target, Exception);
  60. };
  61. export default check;