AccessProvider.tsx
5.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
import {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useState,
type ReactNode,
} from 'react';
import {
defaultMatrix,
roleLabels,
type PermissionMatrix,
type ResourceKey,
type RoleKey,
} from '../model';
import { normalizePermissions, matrixToPoints } from '../backend/adapter';
import { auth } from '../../api/modules/auth';
import { getToken } from '../../api/core/token';
import { getLoginSession, saveLoginSession } from '../session';
/** 登录/info 返回的会话数据(仅取权限相关字段,解耦 access 与具体后端响应结构) */
export interface LoginSession {
roleCodes?: string[];
permCodes?: string[];
}
interface AccessContextValue {
role: RoleKey;
roleCodes: string[];
setRole: (r: RoleKey) => void;
matrix: PermissionMatrix;
/** 页面级权限:门店审批与列表必须有精确 :view,其他资源沿用既有规则。 */
can: (resource: ResourceKey, required?: 'view' | 'full') => boolean;
/** 当前账号持有的权限点集合(后端返回,经适配器归一化) */
points: Set<string>;
/** 按钮/操作级权限判定:是否拥有某个权限点 */
canPoint: (point: string) => boolean;
/** 用后端返回的原始权限数据刷新权限点(经 adapter 归一化) */
loadPermissions: (raw: unknown) => void;
/** 用登录/info 返回的真实权限码注入(后端为权限真源) */
applyLogin: (session: LoginSession) => void;
}
const AccessContext = createContext<AccessContextValue | null>(null);
function sessionRole(codes: string[]): RoleKey {
return codes.find((code): code is RoleKey => Object.hasOwn(roleLabels, code)) ?? 'VIEWER';
}
export function AccessProvider({ children }: { children: ReactNode }) {
const [savedSession] = useState(getLoginSession);
const [role, setRoleState] = useState<RoleKey>(() => sessionRole(savedSession?.roleCodes ?? []));
const [roleCodes, setRoleCodes] = useState<string[]>(savedSession?.roleCodes ?? []);
const [matrix] = useState<PermissionMatrix>(defaultMatrix);
// 刷新时沿用登录返回的真实权限;没有有效会话时不授予业务权限。
const [points, setPoints] = useState<Set<string>>(() => {
const next = new Set(normalizePermissions(savedSession?.permCodes));
if (savedSession) next.add('dashboard');
return next;
});
// 开发兜底:按角色矩阵推导权限点(无后端时本地演示用)
const setRole = (r: RoleKey) => {
setRoleState(r);
setPoints(new Set(matrixToPoints(matrix, r)));
};
// 真实登录:直接用后端返回的权限码(页面/按钮级统一以 points 为准)
const applyLogin = useCallback((session: LoginSession) => {
const codes = session.roleCodes ?? [];
setRoleCodes(codes);
setRoleState(sessionRole(codes));
const next = new Set(normalizePermissions(session));
// 后端未下发 dashboard 权限码,前端按约定补齐:
// 工作台是所有角色的落地页,登录即可见,不该被权限挡住。
//(原 access.manage 权限矩阵调试页已下线:后端菜单树与 permCodes 均无该权限点)
next.add('dashboard');
setPoints(next);
}, []);
const loadPermissions = (raw: unknown) => {
setPoints(new Set(normalizePermissions(raw)));
};
// 刷新/重进:若本地已有令牌,拉取当前用户信息恢复权限(令牌失效由 http 401 处理)
useEffect(() => {
const token = getToken();
if (!token) return;
let active = true;
auth
.info()
.then((info) => {
if (!active || getToken() !== token) return;
const currentSession = getLoginSession();
if (currentSession?.token === token) {
saveLoginSession({
...currentSession,
roleCodes: info.roleCodes ?? [],
permCodes: normalizePermissions(info),
});
}
applyLogin(info);
})
.catch(() => {
/* 忽略:令牌失效时 http 拦截器会清除本地令牌,登录态由路由守卫兜底 */
});
return () => {
active = false;
};
}, [applyLogin]);
const value = useMemo<AccessContextValue>(
() => ({
role,
roleCodes,
setRole,
matrix,
can: (resource, required = 'view') => {
if (required === 'view' && (resource === 'store:approve' || resource === 'store:list')) {
return points.has(`${resource}:view`);
}
if (points.has(resource)) return true;
if (required === 'full') return points.has(`${resource}:manage`);
// 其他资源仍兼容仅下发叶子权限码的情况。
return [...points].some((p) => p.startsWith(`${resource}:`));
},
points,
canPoint: (p: string) => points.has(p),
loadPermissions,
applyLogin,
}),
[role, roleCodes, matrix, points, applyLogin],
);
return <AccessContext.Provider value={value}>{children}</AccessContext.Provider>;
}
export function useAccess(): AccessContextValue {
const ctx = useContext(AccessContext);
if (!ctx) throw new Error('useAccess 必须在 <AccessProvider> 内使用');
return ctx;
}