Authorized.tsx 1.42 KB
Newer Older
1
import Authorized from '@/utils/Authorized';
何乐's avatar
何乐 committed
2
import { ConnectProps, ConnectState, UserModelState } from '@/models/connect';
3 4 5 6
import { connect } from 'dva';
import pathToRegexp from 'path-to-regexp';
import React from 'react';
import Redirect from 'umi/redirect';
何乐's avatar
何乐 committed
7
import { IRoute } from 'umi-types';
8

何乐's avatar
何乐 committed
9
interface AuthComponentProps extends ConnectProps {
10
  location: Location;
何乐's avatar
何乐 committed
11
  routerData: IRoute[];
12 13 14
  user: UserModelState;
}

何乐's avatar
何乐 committed
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
const getRouteAuthority = (path: string, routeData: IRoute[]) => {
  let authorities: string[] | string | undefined = void 0;
  routeData.forEach(route => {
    // match prefix
    if (pathToRegexp(`${route.path}(.*)`).test(path)) {
      authorities = route.authority || authorities;
      // get children authority recursively
      if (route.routes) {
        authorities = getRouteAuthority(path, route.routes) || authorities;
      }
    }
  });
  return authorities;
};

const AuthComponent: React.FC<AuthComponentProps> = ({ children, location, routerData, user }) => {
31 32 33 34
  const { currentUser } = user;
  const isLogin = currentUser && currentUser.name;
  return (
    <Authorized
何乐's avatar
何乐 committed
35
      authority={getRouteAuthority(location.pathname, routerData)!}
36 37 38 39 40 41 42
      noMatch={isLogin ? <Redirect to="/exception/403" /> : <Redirect to="/user/login" />}
    >
      {children}
    </Authorized>
  );
};

何乐's avatar
何乐 committed
43
export default connect(({ menu: menuModel, user }: ConnectState) => ({
44 45 46
  routerData: menuModel.routerData,
  user,
}))(AuthComponent);