Authorized.tsx 1.48 KB
Newer Older
1
import { ConnectProps, ConnectState, Route, UserModelState } from '@/models/connect';
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
2

3 4 5
import Authorized from '@/utils/Authorized';
import React from 'react';
import Redirect from 'umi/redirect';
6 7
import { connect } from 'dva';
import pathToRegexp from 'path-to-regexp';
8

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

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

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

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