Authorized.js 1.1 KB
Newer Older
afc163's avatar
afc163 committed
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';
afc163's avatar
afc163 committed
6

7 8
function AuthComponent({ children, location, routerData, status }) {
  const isLogin = status === 'ok';
kennylbj's avatar
kennylbj committed
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;
afc163's avatar
afc163 committed
15

kennylbj's avatar
kennylbj committed
16 17 18
        // get children authority recursively
        if (route.routes) {
          authorities = getRouteAuthority(path, route.routes) || authorities;
19
        }
kennylbj's avatar
kennylbj committed
20 21 22
      }
    });
    return authorities;
23 24 25 26 27 28 29 30 31 32 33 34 35 36
  };
  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);