Authorized.js 1.1 KB
Newer Older
A
afc163 已提交
1
import React from 'react';
陈帅 已提交
2
import Redirect from 'umi/redirect';
陈小聪 已提交
3 4 5
import pathToRegexp from 'path-to-regexp';
import { connect } from 'dva';
import Authorized from '@/utils/Authorized';
A
afc163 已提交
6

陈小聪 已提交
7 8
function AuthComponent({ children, location, routerData, status }) {
  const isLogin = status === 'ok';
K
kennylbj 已提交
9 10 11 12 13 14
  const getRouteAuthority = (path, routeData) => {
    let authorities;
    routeData.forEach(route => {
      // match prefix
      if (pathToRegexp(`${route.path}(.*)`).test(path)) {
        authorities = route.authority || authorities;
A
afc163 已提交
15

K
kennylbj 已提交
16 17 18
        // get children authority recursively
        if (route.routes) {
          authorities = getRouteAuthority(path, route.routes) || authorities;
陈小聪 已提交
19
        }
K
kennylbj 已提交
20 21 22
      }
    });
    return authorities;
陈小聪 已提交
23
  };
陈小聪 已提交
24

陈小聪 已提交
25 26 27 28 29 30 31 32 33 34 35 36 37
  return (
    <Authorized
      authority={getRouteAuthority(location.pathname, routerData)}
      noMatch={isLogin ? <Redirect to="/exception/403" /> : <Redirect to="/user/login" />}
    >
      {children}
    </Authorized>
  );
}
export default connect(({ menu: menuModel, login: loginModel }) => ({
  routerData: menuModel.routerData,
  status: loginModel.status,
}))(AuthComponent);