Authorized.tsx
1.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import React from 'react';
import Redirect from 'umi/redirect';
import { connect } from 'dva';
import pathToRegexp from 'path-to-regexp';
import Authorized from '@/utils/Authorized';
import { ConnectProps, ConnectState, Route, UserModelState } from '@/models/connect';
interface AuthComponentProps extends ConnectProps {
user: UserModelState;
}
const getRouteAuthority = (path: string, routeData: Route[]) => {
let authorities: string[] | string | undefined;
routeData.forEach(route => {
if (route.authority) {
authorities = route.authority;
}
// match prefix
if (pathToRegexp(`${route.path}(.*)`).test(path)) {
// exact match
if (route.path === path) {
authorities = route.authority || authorities;
}
// get children authority recursively
if (route.routes) {
authorities = getRouteAuthority(path, route.routes) || authorities;
}
}
});
return authorities;
};
const AuthComponent: React.FC<AuthComponentProps> = ({
children,
route = {
routes: [],
},
location = {
pathname: '',
},
user,
}) => {
const { currentUser } = user;
const { routes = [] } = route;
const isLogin = currentUser && currentUser.name;
return (
<Authorized
authority={getRouteAuthority(location.pathname, routes) || ''}
noMatch={isLogin ? <Redirect to="/exception/403" /> : <Redirect to="/user/login" />}
>
{children}
</Authorized>
);
};
export default connect(({ user }: ConnectState) => ({
user,
}))(AuthComponent);