CheckPermissions.js 1.88 KB
Newer Older
ddcat1115's avatar
ddcat1115 committed
1 2
import React from 'react';
import PromiseRender from './PromiseRender';
3
import { CURRENT } from './renderAuthorize';
afc163's avatar
afc163 committed
4 5

function isPromise(obj) {
6 7 8 9 10
  return (
    !!obj &&
    (typeof obj === 'object' || typeof obj === 'function') &&
    typeof obj.then === 'function'
  );
afc163's avatar
afc163 committed
11 12
}

ddcat1115's avatar
ddcat1115 committed
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
/**
 * ้€š็”จๆƒ้™ๆฃ€ๆŸฅๆ–นๆณ•
 * 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
28 29
  if (Array.isArray(authority)) {
    if (authority.indexOf(currentAuthority) >= 0) {
ddcat1115's avatar
ddcat1115 committed
30 31 32 33 34 35
      return target;
    }
    return Exception;
  }

  // string ๅค„็†
afc163's avatar
afc163 committed
36
  if (typeof authority === 'string') {
ddcat1115's avatar
ddcat1115 committed
37 38 39 40 41 42 43
    if (authority === currentAuthority) {
      return target;
    }
    return Exception;
  }

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

  // Function ๅค„็†
afc163's avatar
afc163 committed
49
  if (typeof authority === 'function') {
ddcat1115's avatar
ddcat1115 committed
50
    try {
้™ˆๅธ…'s avatar
้™ˆๅธ… committed
51
      const bool = authority(currentAuthority);
52 53 54 55
      // ๅ‡ฝๆ•ฐๆ‰ง่กŒๅŽ่ฟ”ๅ›žๅ€ผๆ˜ฏ Promise
      if (isPromise(bool)) {
        return <PromiseRender ok={target} error={Exception} promise={bool} />;
      }
ddcat1115's avatar
ddcat1115 committed
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
      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;