CheckPermissions.js 1.69 KB
Newer Older
ddcat1115's avatar
ddcat1115 committed
1 2 3
import React from 'react';
import PromiseRender from './PromiseRender';
import { CURRENT } from './index';
afc163's avatar
afc163 committed
4 5 6 7 8

function isPromise(obj) {
  return !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function';
}

ddcat1115's avatar
ddcat1115 committed
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/**
 * ้€š็”จๆƒ้™ๆฃ€ๆŸฅๆ–นๆณ•
 * Common check permissions method
 * @param { ๆƒ้™ๅˆคๅฎš Permission judgment type string |array | Promise | Function } authority
 * @param { ไฝ ็š„ๆƒ้™ Your permission description  type:string} currentAuthority
 * @param { ้€š่ฟ‡็š„็ป„ไปถ Passing components } target
 * @param { ๆœช้€š่ฟ‡็š„็ป„ไปถ no pass components } Exception
 */
const checkPermissions = (authority, currentAuthority, target, Exception) => {
  // ๆฒกๆœ‰ๅˆคๅฎšๆƒ้™.้ป˜่ฎคๆŸฅ็œ‹ๆ‰€ๆœ‰
  // Retirement authority, return target;
  if (!authority) {
    return target;
  }
  // ๆ•ฐ็ป„ๅค„็†
afc163's avatar
afc163 committed
24 25
  if (Array.isArray(authority)) {
    if (authority.indexOf(currentAuthority) >= 0) {
ddcat1115's avatar
ddcat1115 committed
26 27 28 29 30 31
      return target;
    }
    return Exception;
  }

  // string ๅค„็†
afc163's avatar
afc163 committed
32
  if (typeof authority === 'string') {
ddcat1115's avatar
ddcat1115 committed
33 34 35 36 37 38 39
    if (authority === currentAuthority) {
      return target;
    }
    return Exception;
  }

  // Promise ๅค„็†
afc163's avatar
afc163 committed
40
  if (isPromise(authority)) {
41
    return <PromiseRender ok={target} error={Exception} promise={authority} />;
ddcat1115's avatar
ddcat1115 committed
42 43 44
  }

  // Function ๅค„็†
afc163's avatar
afc163 committed
45
  if (typeof authority === 'function') {
ddcat1115's avatar
ddcat1115 committed
46
    try {
้™ˆๅธ…'s avatar
้™ˆๅธ… committed
47
      const bool = authority(currentAuthority);
ddcat1115's avatar
ddcat1115 committed
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
      if (bool) {
        return target;
      }
      return Exception;
    } catch (error) {
      throw error;
    }
  }
  throw new Error('unsupported parameters');
};

export { checkPermissions };

const check = (authority, target, Exception) => {
  return checkPermissions(authority, CURRENT, target, Exception);
};

export default check;