| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 |
- import { createContext, useContext, useState, useEffect } from "react";
- import type { ReactNode } from "react";
- import type { JeecgMenu } from "@/types/menu";
- import { getUserPermissions } from "@/services/api";
- import { isPublicRoute } from "@/router/publicRoutes.tsx";
- interface AuthContextType {
- menus: JeecgMenu[];
- permissions: Map<string, string[]>; // menuId -> actions[]
- loading: boolean;
- hasPermission: (menuId: string, action: string) => boolean;
- refreshAuth: () => Promise<void>;
- }
- const AuthContext = createContext<AuthContextType | undefined>(undefined);
- export function AuthProvider({ children }: { children: ReactNode }) {
- const [menus, setMenus] = useState<JeecgMenu[]>([]);
- const [permissions] = useState<Map<string, string[]>>(
- new Map()
- );
- const [loading, setLoading] = useState(true);
- const loadAuthData = async () => {
- try {
- setLoading(true);
- const [menusData] = await Promise.all([
- getUserPermissions(),
- ]);
- setMenus(menusData.menu);
- } catch (error) {
- console.error("加载权限数据失败:", error);
- } finally {
- setLoading(false);
- }
- };
- useEffect(() => {
- // 如果在公开路由页面,跳过权限加载
- const currentPath = window.location.pathname;
- if (isPublicRoute(currentPath)) {
- setLoading(false);
- return;
- }
-
- loadAuthData();
- }, []);
- const hasPermission = (menuId: string, action: string): boolean => {
- const actions = permissions.get(menuId);
- return actions ? actions.includes(action) : false;
- };
- return (
- <AuthContext.Provider
- value={{
- menus,
- permissions,
- loading,
- hasPermission,
- refreshAuth: loadAuthData,
- }}
- >
- {children}
- </AuthContext.Provider>
- );
- }
- export function useAuth() {
- const context = useContext(AuthContext);
- if (!context) {
- throw new Error("useAuth must be used within AuthProvider");
- }
- return context;
- }
|