Secured.jsx 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import React from 'react';
  2. import CheckPermissions from './CheckPermissions';
  3. /**
  4. * 默认不能访问任何页面
  5. * default is "NULL"
  6. */
  7. const Exception403 = () => 403;
  8. export const isComponentClass = component => {
  9. if (!component) return false;
  10. const proto = Object.getPrototypeOf(component);
  11. if (proto === React.Component || proto === Function.prototype) return true;
  12. return isComponentClass(proto);
  13. }; // Determine whether the incoming component has been instantiated
  14. // AuthorizedRoute is already instantiated
  15. // Authorized render is already instantiated, children is no instantiated
  16. // Secured is not instantiated
  17. const checkIsInstantiation = target => {
  18. if (isComponentClass(target)) {
  19. const Target = target;
  20. return props => <Target {...props} />;
  21. }
  22. if (React.isValidElement(target)) {
  23. return props => React.cloneElement(target, props);
  24. }
  25. return () => target;
  26. };
  27. /**
  28. * 用于判断是否拥有权限访问此 view 权限
  29. * authority 支持传入 string, () => boolean | Promise
  30. * e.g. 'user' 只有 user 用户能访问
  31. * e.g. 'user,admin' user 和 admin 都能访问
  32. * e.g. ()=>boolean 返回true能访问,返回false不能访问
  33. * e.g. Promise then 能访问 catch不能访问
  34. * e.g. authority support incoming string, () => boolean | Promise
  35. * e.g. 'user' only user user can access
  36. * e.g. 'user, admin' user and admin can access
  37. * e.g. () => boolean true to be able to visit, return false can not be accessed
  38. * e.g. Promise then can not access the visit to catch
  39. * @param {string | function | Promise} authority
  40. * @param {ReactNode} error 非必需参数
  41. */
  42. const authorize = (authority, error) => {
  43. /**
  44. * conversion into a class
  45. * 防止传入字符串时找不到staticContext造成报错
  46. * String parameters can cause staticContext not found error
  47. */
  48. let classError = false;
  49. if (error) {
  50. classError = () => error;
  51. }
  52. if (!authority) {
  53. throw new Error('authority is required');
  54. }
  55. return function decideAuthority(target) {
  56. const component = CheckPermissions(authority, target, classError || Exception403);
  57. return checkIsInstantiation(component);
  58. };
  59. };
  60. export default authorize;