CheckPermissions.tsx 2.37 KB
Newer Older
้™ˆๅธ…'s avatar
้™ˆๅธ… committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
import React from 'react';
// eslint-disable-next-line import/no-cycle
import PromiseRender from './PromiseRender';
import { CURRENT } from './renderAuthorize';

export type IAuthorityType =
  | string
  | string[]
  | Promise<any>
  | ((currentAuthority: string | string[]) => IAuthorityType);

/**
 * ้€š็”จๆƒ้™ๆฃ€ๆŸฅๆ–นๆณ•
 * Common check permissions method
 * @param { ๆƒ้™ๅˆคๅฎš | Permission judgment } authority
 * @param { ไฝ ็š„ๆƒ้™ | Your permission description } currentAuthority
 * @param { ้€š่ฟ‡็š„็ป„ไปถ | Passing components } target
 * @param { ๆœช้€š่ฟ‡็š„็ป„ไปถ | no pass components } Exception
 */
const checkPermissions = (
  authority: IAuthorityType,
  currentAuthority: string | string[],
  target: React.ComponentClass<any, any> | React.ReactNode,
  Exception: React.ReactNode,
): React.ReactNode => {
  // ๆฒกๆœ‰ๅˆคๅฎšๆƒ้™.้ป˜่ฎคๆŸฅ็œ‹ๆ‰€ๆœ‰
  // Retirement authority, return target;
  if (!authority) {
    return target;
  }
  // ๆ•ฐ็ป„ๅค„็†
  if (Array.isArray(authority)) {
    if (Array.isArray(currentAuthority)) {
      if (currentAuthority.some(item => authority.includes(item))) {
        return target;
      }
    } else if (authority.includes(currentAuthority)) {
      return target;
    }
    return Exception;
  }
  // string ๅค„็†
  if (typeof authority === 'string') {
    if (Array.isArray(currentAuthority)) {
      if (currentAuthority.some(item => authority === item)) {
        return target;
      }
    } else if (authority === currentAuthority) {
      return target;
    }
    return Exception;
  }
  // Promise ๅค„็†
  if (authority instanceof Promise) {
    return <PromiseRender ok={target} error={Exception} promise={authority} />;
  }
  // Function ๅค„็†
  if (typeof authority === 'function') {
    try {
      const bool = authority(currentAuthority);
      // ๅ‡ฝๆ•ฐๆ‰ง่กŒๅŽ่ฟ”ๅ›žๅ€ผๆ˜ฏ Promise
      if (bool instanceof Promise) {
        return <PromiseRender ok={target} error={Exception} promise={bool} />;
      }
      if (bool) {
        return target;
      }
      return Exception;
    } catch (error) {
      throw error;
    }
  }
  throw new Error('unsupported parameters');
};

export { checkPermissions };

const check = (
  authority: IAuthorityType,
  target: React.ComponentClass<any, any> | React.ReactNode,
  Exception: React.ReactNode,
): React.ReactNode => checkPermissions(authority, CURRENT, target, Exception);

export default check;