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

ddcat1115's avatar
ddcat1115 committed
5 6 7
/**
 * 通用权限检查方法
 * Common check permissions method
8 9 10 11
 * @param { 权限判定 | Permission judgment } authority
 * @param { 你的权限 | Your permission description } currentAuthority
 * @param { 通过的组件 | Passing components } target
 * @param { 未通过的组件 | no pass components } Exception
ddcat1115's avatar
ddcat1115 committed
12 13 14 15 16 17 18 19
 */
const checkPermissions = (authority, currentAuthority, target, Exception) => {
  // 没有判定权限.默认查看所有
  // Retirement authority, return target;
  if (!authority) {
    return target;
  }
  // 数组处理
afc163's avatar
afc163 committed
20
  if (Array.isArray(authority)) {
21
    if (Array.isArray(currentAuthority)) {
22 23
      if (currentAuthority.some(item => authority.includes(item))) {
        return target;
24
      }
25 26
    } else if (authority.includes(currentAuthority)) {
      return target;
27
    }
ddcat1115's avatar
ddcat1115 committed
28 29 30
    return Exception;
  }
  // string 处理
afc163's avatar
afc163 committed
31
  if (typeof authority === 'string') {
32
    if (Array.isArray(currentAuthority)) {
33 34
      if (currentAuthority.some(item => authority === item)) {
        return target;
35
      }
36 37
    } else if (authority === currentAuthority) {
      return target;
38
    }
ddcat1115's avatar
ddcat1115 committed
39 40 41
    return Exception;
  }
  // Promise 处理
42
  if (authority instanceof Promise) {
43
    return <PromiseRender ok={target} error={Exception} promise={authority} />;
ddcat1115's avatar
ddcat1115 committed
44 45
  }
  // Function 处理
afc163's avatar
afc163 committed
46
  if (typeof authority === 'function') {
ddcat1115's avatar
ddcat1115 committed
47
    try {
陈帅's avatar
陈帅 committed
48
      const bool = authority(currentAuthority);
49
      // 函数执行后返回值是 Promise
50
      if (bool instanceof Promise) {
51 52
        return <PromiseRender ok={target} error={Exception} promise={bool} />;
      }
ddcat1115's avatar
ddcat1115 committed
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 };

66 67
const check = (authority, target, Exception) =>
  checkPermissions(authority, CURRENT, target, Exception);
ddcat1115's avatar
ddcat1115 committed
68 69

export default check;