菜单权限
This commit is contained in:
@@ -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 />;
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user