Authorized.tsx 1.4 KB

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