菜单权限

This commit is contained in:
liamzi
2025-01-14 18:52:03 +08:00
parent 2edb91cbea
commit 34550d0517
10 changed files with 790 additions and 409 deletions

View File

@@ -1,24 +1,27 @@
import React from "react";
import { Navigate, useLocation } from "react-router-dom";
import { useAuth } from "@/contexts/AuthContext";
import { Spin } from "antd";
const PUBLIC_PATHS = ['login', '404'];
export const ProtectedRoute = ({ children }) => {
const { user, loading } = useAuth();
const { user } = useAuth();
const location = useLocation();
if (loading) {
return (
<div className="min-h-screen flex items-center justify-center">
<Spin size="large" />
</div>
);
const currentPath = location.pathname.replace(/^\//, '');
if (PUBLIC_PATHS.includes(currentPath) || currentPath === '*') {
return children;
}
if (user?.id) {
const hasPermission = user.menukeys?.some(key => {
return currentPath === key || currentPath.startsWith(`${key}/`);
});
if (!hasPermission ) {
return <Navigate to="/404" replace />;
}
return children;
}
if (!user?.id) {
return (
<Navigate to={`/login?redirectTo=${location.pathname || ""}`} replace />
);
}
return children;
// 如果用户未登录,重定向到登录页
return <Navigate to="/login" state={{ from: location }} replace />;
};