authWrapper.tsx 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /*
  2. * @Author: code4eat awesomedema@gmail.com
  3. * @Date: 2024-07-17 10:36:43
  4. * @LastEditors: code4eat awesomedema@gmail.com
  5. * @LastEditTime: 2024-07-18 16:41:08
  6. * @FilePath: /BudgetManaSystem/src/authWrapper.tsx
  7. * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
  8. */
  9. // src/components/AuthWrapper.tsx
  10. import React, { useEffect, useState } from 'react';
  11. import { history, useModel } from 'umi';
  12. import type { IRoute } from 'umi';
  13. import { Outlet } from '@umijs/max';
  14. // 权限检查函数
  15. function checkAccess(menu: IRoute[], pathname: string): boolean {
  16. for (const item of menu) {
  17. if (item.path === pathname) {
  18. return true;
  19. }
  20. if (item.children) {
  21. const hasAccess = checkAccess(item.children, pathname);
  22. if (hasAccess) {
  23. return true;
  24. }
  25. }
  26. }
  27. return false;
  28. }
  29. function removePrefix(input: string, prefix: string): string {
  30. if (input.startsWith(prefix)) {
  31. return input.slice(prefix.length);
  32. }
  33. return input;
  34. }
  35. // 权限包装组件
  36. const AuthWrapper: React.FC = (props) => {
  37. const { initialState } = useModel('@@initialState');
  38. const [loading, setLoading] = useState(true);
  39. const [dataLoaded, setDataLoaded] = useState(false);
  40. useEffect(() => {
  41. if (!dataLoaded) {
  42. const menu = initialState?.memuData ?? [];
  43. if (menu.length > 0) {
  44. setDataLoaded(true);
  45. const { pathname } = history.location;
  46. const hasAccess = checkAccess(menu, removePrefix(pathname, '/budgetManaSystem'));
  47. // console.log({ hasAccess, menu, pathname });
  48. if (!hasAccess) {
  49. history.push('/noAccess');
  50. }
  51. setLoading(false);
  52. }
  53. }
  54. }, [initialState,dataLoaded]);
  55. return loading ? <>loading...</> : <Outlet />;
  56. };
  57. export default AuthWrapper;
  58. export { checkAccess };