Secured.js 1.9 KB

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