Authorized.tsx 2 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 23 24 25 26 27
      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
28 29 30 31 32 33 34 35 36
      // get children authority recursively
      if (route.routes) {
        authorities = getRouteAuthority(path, route.routes) || authorities;
      }
    }
  });
  return authorities;
};

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

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

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