Secured.tsx 2.39 KB
Newer Older
陈帅's avatar
陈帅 committed
1 2 3 4 5 6 7 8 9
import React from 'react';
import CheckPermissions from './CheckPermissions';

/**
 * 默认不能访问任何页面
 * default is "NULL"
 */
const Exception403 = () => 403;

陈帅's avatar
陈帅 committed
10
export const isComponentClass = (component: React.ComponentClass | React.ReactNode): boolean => {
陈帅's avatar
陈帅 committed
11 12 13 14 15 16 17 18 19 20
  if (!component) return false;
  const proto = Object.getPrototypeOf(component);
  if (proto === React.Component || proto === Function.prototype) return true;
  return isComponentClass(proto);
};

// Determine whether the incoming component has been instantiated
// AuthorizedRoute is already instantiated
// Authorized  render is already instantiated, children is no instantiated
// Secured is not instantiated
陈帅's avatar
陈帅 committed
21
const checkIsInstantiation = (target: React.ComponentClass | React.ReactNode) => {
陈帅's avatar
陈帅 committed
22
  if (isComponentClass(target)) {
陈帅's avatar
陈帅 committed
23
    const Target = target as React.ComponentClass;
陈帅's avatar
陈帅 committed
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
    return (props: any) => <Target {...props} />;
  }
  if (React.isValidElement(target)) {
    return (props: any) => React.cloneElement(target, props);
  }
  return () => target;
};

/**
 * 用于判断是否拥有权限访问此 view 权限
 * authority 支持传入 string, () => boolean | Promise
 * e.g. 'user' 只有 user 用户能访问
 * e.g. 'user,admin' user 和 admin 都能访问
 * e.g. ()=>boolean 返回true能访问,返回false不能访问
 * e.g. Promise  then 能访问   catch不能访问
 * e.g. authority support incoming string, () => boolean | Promise
 * e.g. 'user' only user user can access
 * e.g. 'user, admin' user and admin can access
 * e.g. () => boolean true to be able to visit, return false can not be accessed
 * e.g. Promise then can not access the visit to catch
 * @param {string | function | Promise} authority
 * @param {ReactNode} error 非必需参数
 */
const authorize = (authority: string, error?: React.ReactNode) => {
  /**
   * conversion into a class
   * 防止传入字符串时找不到staticContext造成报错
   * String parameters can cause staticContext not found error
   */
陈帅's avatar
陈帅 committed
53
  let classError: boolean | React.FunctionComponent = false;
陈帅's avatar
陈帅 committed
54
  if (error) {
陈帅's avatar
陈帅 committed
55
    classError = (() => error) as React.FunctionComponent;
陈帅's avatar
陈帅 committed
56 57 58 59
  }
  if (!authority) {
    throw new Error('authority is required');
  }
陈帅's avatar
陈帅 committed
60
  return function decideAuthority(target: React.ComponentClass | React.ReactNode) {
陈帅's avatar
陈帅 committed
61 62 63 64 65 66
    const component = CheckPermissions(authority, target, classError || Exception403);
    return checkIsInstantiation(component);
  };
};

export default authorize;