Authorized.tsx 1.82 KB
Newer Older
1 2
import React from 'react';
import Redirect from 'umi/redirect';
3 4
import { connect } from 'dva';
import pathToRegexp from 'path-to-regexp';
้™ˆๅธ…'s avatar
้™ˆๅธ… committed
5 6
import Authorized from '@/utils/Authorized';
import { ConnectProps, ConnectState, Route, UserModelState } from '@/models/connect';
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)) {
duanledexianxianxian's avatar
sync  
duanledexianxianxian committed
17 18 19 20 21 22
      authorities = route.authority || authorities;
      // ๅฎ˜ๆ–นไปฃ็ ๅฅฝๅƒๆœ‰้—ฎ้ข˜https://github.com/ant-design/ant-design-pro/commit/4a10734dcf858c6363af719a5886a24ec1115b33#diff-2041540b332693486a24a543b6ba0cc8
      // // exact match
      // if (route.path === path) {
      //   authorities = route.authority || authorities;
      // }
ไฝ•ไน's avatar
ไฝ•ไน committed
23 24 25 26 27 28 29 30 31
      // get children authority recursively
      if (route.routes) {
        authorities = getRouteAuthority(path, route.routes) || authorities;
      }
    }
  });
  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
  const isLogin = currentUser && currentUser.name;
duanledexianxianxian's avatar
sync  
duanledexianxianxian committed
45 46 47 48
  console.log('routes:', location.pathname, routes);
  console.log('authority:', getRouteAuthority(location.pathname, routes));
  console.log('isLogin:', isLogin);

49 50
  return (
    <Authorized
51
      authority={getRouteAuthority(location.pathname, routes) || ''}
52 53 54 55 56 57 58
      noMatch={isLogin ? <Redirect to="/exception/403" /> : <Redirect to="/user/login" />}
    >
      {children}
    </Authorized>
  );
};

้™ˆๅธ…'s avatar
้™ˆๅธ… committed
59
export default connect(({ user }: ConnectState) => ({
60 61
  user,
}))(AuthComponent);