41 lines
1.3 KiB
TypeScript
41 lines
1.3 KiB
TypeScript
import React from 'react';
|
|
import { Result, Button, Spin } from 'antd';
|
|
import { useNavigate } from 'react-router';
|
|
import { findRoleAwareLandingPath } from '../auth/menu-policy';
|
|
import { usePermission } from '../hooks/usePermission';
|
|
import { useUserStore } from '../store/user/userStore';
|
|
|
|
interface PermissionRouteProps {
|
|
permission: string;
|
|
children: React.ReactNode;
|
|
}
|
|
|
|
const PermissionRoute: React.FC<PermissionRouteProps> = ({ permission, children }) => {
|
|
const { permissions, permissionsReady, hasPermission } = usePermission();
|
|
const roles = useUserStore((state) => state.user?.roles ?? []);
|
|
const navigate = useNavigate();
|
|
if (!permissionsReady) {
|
|
return <Spin size="large" style={{ display: 'block', margin: '80px auto' }} />;
|
|
}
|
|
if (!hasPermission(permission)) {
|
|
const firstPath = findRoleAwareLandingPath(roles, permissions);
|
|
return (
|
|
<Result
|
|
status="403"
|
|
title="无权访问"
|
|
subTitle="您没有访问此页面的权限"
|
|
extra={
|
|
firstPath ? (
|
|
<Button type="primary" onClick={() => navigate(firstPath, { replace: true })}>
|
|
前往可访问页面
|
|
</Button>
|
|
) : undefined
|
|
}
|
|
/>
|
|
);
|
|
}
|
|
return <>{children}</>;
|
|
};
|
|
|
|
export default PermissionRoute;
|