12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 |
- /*
- * @Author: code4eat awesomedema@gmail.com
- * @Date: 2024-07-17 10:36:43
- * @LastEditors: code4eat awesomedema@gmail.com
- * @LastEditTime: 2024-07-18 16:41:08
- * @FilePath: /BudgetManaSystem/src/authWrapper.tsx
- * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
- */
- // src/components/AuthWrapper.tsx
- import React, { useEffect, useState } from 'react';
- import { history, useModel } from 'umi';
- import type { IRoute } from 'umi';
- import { Outlet } from '@umijs/max';
- // 权限检查函数
- function checkAccess(menu: IRoute[], pathname: string): boolean {
- for (const item of menu) {
- if (item.path === pathname) {
- return true;
- }
- if (item.children) {
- const hasAccess = checkAccess(item.children, pathname);
- if (hasAccess) {
- return true;
- }
- }
- }
- return false;
- }
- function removePrefix(input: string, prefix: string): string {
- if (input.startsWith(prefix)) {
- return input.slice(prefix.length);
- }
- return input;
- }
- // 权限包装组件
- const AuthWrapper: React.FC = (props) => {
- const { initialState } = useModel('@@initialState');
- const [loading, setLoading] = useState(true);
- const [dataLoaded, setDataLoaded] = useState(false);
-
- useEffect(() => {
- if (!dataLoaded) {
- const menu = initialState?.memuData ?? [];
- if (menu.length > 0) {
- setDataLoaded(true);
- const { pathname } = history.location;
- const hasAccess = checkAccess(menu, removePrefix(pathname, '/budgetManaSystem'));
- // console.log({ hasAccess, menu, pathname });
- if (!hasAccess) {
- history.push('/noAccess');
- }
- setLoading(false);
- }
- }
- }, [initialState,dataLoaded]);
-
- return loading ? <>loading...</> : <Outlet />;
- };
- export default AuthWrapper;
- export { checkAccess };
|