Authorized.tsx 2 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)) {
duanledexianxianxian's avatar
sync  
duanledexianxianxian committed
18 19 20 21 22 23 24 25 26 27 28
      console.log('----------------------');
      console.log('route.path:', route.path);
      console.log('path:', path);
      console.log('route.authority:', route.authority);

      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
29 30 31 32 33 34 35 36 37
      // get children authority recursively
      if (route.routes) {
        authorities = getRouteAuthority(path, route.routes) || authorities;
      }
    }
  });
  return authorities;
};

้™ˆๅธ…'s avatar
้™ˆๅธ… committed
38 39 40 41 42
const AuthComponent: React.FC<AuthComponentProps> = ({
  children,
  route = {
    routes: [],
  },
43 44 45
  location = {
    pathname: '',
  },
้™ˆๅธ…'s avatar
้™ˆๅธ… committed
46 47
  user,
}) => {
48
  const { currentUser } = user;
้™ˆๅธ…'s avatar
้™ˆๅธ… committed
49
  const { routes = [] } = route;
50
  const isLogin = currentUser && currentUser.name;
duanledexianxianxian's avatar
sync  
duanledexianxianxian committed
51 52 53 54
  console.log('routes:', location.pathname, routes);
  console.log('authority:', getRouteAuthority(location.pathname, routes));
  console.log('isLogin:', isLogin);

55 56
  return (
    <Authorized
57
      authority={getRouteAuthority(location.pathname, routes) || ''}
58 59 60 61 62 63 64
      noMatch={isLogin ? <Redirect to="/exception/403" /> : <Redirect to="/user/login" />}
    >
      {children}
    </Authorized>
  );
};

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