authWrapper.tsx 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // src/components/AuthWrapper.tsx
  2. import React, { useEffect, useState } from 'react';
  3. import { history, useModel } from 'umi';
  4. import type { IRoute } from 'umi';
  5. import { Outlet } from '@umijs/max';
  6. // 权限检查函数
  7. function checkAccess(menu: IRoute[], pathname: string): boolean {
  8. for (const item of menu) {
  9. if (item.path === pathname) {
  10. return true;
  11. }
  12. if (item.children) {
  13. const hasAccess = checkAccess(item.children, pathname);
  14. if (hasAccess) {
  15. return true;
  16. }
  17. }
  18. }
  19. return false;
  20. }
  21. function removePrefix(input: string, prefix: string): string {
  22. if (input.startsWith(prefix)) {
  23. return input.slice(prefix.length);
  24. }
  25. return input;
  26. }
  27. // 权限包装组件
  28. const AuthWrapper: React.FC = (props) => {
  29. const { initialState } = useModel('@@initialState');
  30. const [loading, setLoading] = useState(true);
  31. const [dataLoaded, setDataLoaded] = useState(false);
  32. useEffect(() => {
  33. if (!dataLoaded) {
  34. const menu = initialState?.memuData ?? [];
  35. if (menu.length > 0) {
  36. setDataLoaded(true);
  37. const { pathname } = history.location;
  38. const hasAccess = checkAccess(menu, removePrefix(pathname, '/CostAccountingSys'));
  39. // console.log({ hasAccess, menu, pathname });
  40. if (!hasAccess) {
  41. history.push('/noAccess');
  42. }
  43. setLoading(false);
  44. }
  45. }
  46. }, [initialState, dataLoaded]);
  47. return loading ? <>loading...</> : <Outlet />;
  48. };
  49. export default AuthWrapper;
  50. export { checkAccess };