Authorized.tsx 1.43 KB
Newer Older
1
import { ConnectProps, ConnectState, Route, UserModelState } from '@/models/connect';
2 3 4
import Authorized from '@/utils/Authorized';
import React from 'react';
import Redirect from 'umi/redirect';
5 6
import { connect } from 'dva';
import pathToRegexp from 'path-to-regexp';
7

何乐's avatar
何乐 committed
8
interface AuthComponentProps extends ConnectProps {
9 10 11
  user: UserModelState;
}

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

ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
30 31 32 33 34
const AuthComponent: React.FC<AuthComponentProps> = ({
  children,
  route = {
    routes: [],
  },
35 36 37
  location = {
    pathname: '',
  },
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
38 39
  user,
}) => {
40
  const { currentUser } = user;
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
41
  const { routes = [] } = route;
42 43 44
  const isLogin = currentUser && currentUser.name;
  return (
    <Authorized
45
      authority={getRouteAuthority(location.pathname, routes) || ''}
46 47 48 49 50 51 52
      noMatch={isLogin ? <Redirect to="/exception/403" /> : <Redirect to="/user/login" />}
    >
      {children}
    </Authorized>
  );
};

ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
53
export default connect(({ user }: ConnectState) => ({
54 55
  user,
}))(AuthComponent);