This commit is contained in:
liamzi
2025-01-17 17:39:14 +08:00
parent f1fe46b11a
commit c229f2dbc4
2 changed files with 37 additions and 16 deletions

View File

@@ -3,13 +3,26 @@ import { Navigate, useLocation } from "react-router-dom";
import { useAuth } from "@/contexts/AuthContext";
const PUBLIC_PATHS = ['login', '404','home'];
export const ProtectedRoute = ({ children }) => {
const { user } = useAuth();
const location = useLocation();
const currentPath = location.pathname.replace(/^\//, '');
// 如果是公共路径,直接显示
if (PUBLIC_PATHS.includes(currentPath) || currentPath === '*') {
return children;
}
// 如果用户未登录,重定向到登录页面,并携带当前路径
if (!user?.id) {
return <Navigate
to={`/login?redirectTo=${encodeURIComponent(location.pathname + location.search)}`}
replace
/>;
}
// 如果用户已登录,检查权限
if (user?.id) {
const hasPermission = user.menukeys?.some(key => {
return currentPath === key || currentPath.startsWith(`${key}/`);