Authorized.tsx 1.35 KB
Newer Older
1
import Authorized from '@/utils/Authorized';
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
2
import { ConnectProps, ConnectState, UserModelState, Route } from '@/models/connect';
3 4 5 6 7
import { connect } from 'dva';
import pathToRegexp from 'path-to-regexp';
import React from 'react';
import Redirect from 'umi/redirect';

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

12
const getRouteAuthority = (path: string, routeData: Route[]) => {
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
13
  let authorities: string[] | string | undefined = undefined;
何乐's avatar
何乐 committed
14 15 16 17 18 19 20 21 22 23 24 25 26
  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;
};

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

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