AccessProvider.tsx
4.74 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
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 {
canByPoints,
canPointByPoints,
readPermCodes,
readSession,
shortName,
subappBus,
} from '../../../subapp';
import { busEvents } from '@uj/contracts';
/**
* 子应用版 AccessProvider:与 host 的 useAccess() 接口逐项对齐,但实现是纯本地的。
*
* 与 host 版的三点差异(都是 wujie 隔离的必然结果):
* 1. 不调用 auth.info() —— 权限真源是 localStorage(同源 iframe 可读)与 props.session,
* 每个子应用各拉一次 info 既浪费又会各自处理 401;
* 2. Context 是子应用自己的 createContext,不可能与 host 共享;
* 3. 权限 / 会话变更靠 bus 广播刷新,而不是靠 React 状态提升。
*
* 页面里 `useAccess()` / `<PermButton point={P.X}>` 因此一个字都不用改。
*/
export interface AccessContextValue {
role: RoleKey;
roleCodes: string[];
setRole: (r: RoleKey) => void;
matrix: PermissionMatrix;
can: (resource: ResourceKey, required?: 'view' | 'full') => boolean;
points: Set<string>;
canPoint: (point: string) => boolean;
loadPermissions: (raw: unknown) => void;
applyLogin: (session: { roleCodes?: string[]; permCodes?: string[] }) => void;
}
const AccessContext = createContext<AccessContextValue | null>(null);
function sessionRole(codes: string[]): RoleKey {
return codes.find((code): code is RoleKey => Object.hasOwn(roleLabels, code)) ?? 'VIEWER';
}
function initialPoints(): Set<string> {
const next = new Set(normalizePermissions(readPermCodes()));
// 工作台是所有角色的落地页;后端菜单树可能不下发 dashboard 权限码,前端按约定补齐。
if (readSession()) next.add('dashboard');
return next;
}
export function AccessProvider({ children }: { children: ReactNode }) {
const [roleCodes, setRoleCodes] = useState<string[]>(() => readSession()?.roleCodes ?? []);
const [role, setRoleState] = useState<RoleKey>(() => sessionRole(readSession()?.roleCodes ?? []));
const [matrix] = useState<PermissionMatrix>(defaultMatrix);
const [points, setPoints] = useState<Set<string>>(initialPoints);
// 与 host 版一致:固定 setRole 引用,避免 useMemo 的 value 每次 render 都变。
const setRole = useCallback(
(r: RoleKey) => {
setRoleState(r);
setPoints(new Set(matrixToPoints(matrix, r)));
},
[matrix],
);
const applyLogin = useCallback((session: { roleCodes?: string[]; permCodes?: string[] }) => {
const codes = session.roleCodes ?? [];
setRoleCodes(codes);
setRoleState(sessionRole(codes));
const next = new Set(normalizePermissions(session));
next.add('dashboard');
setPoints(next);
}, []);
const loadPermissions = useCallback(
(raw: unknown) => setPoints(new Set(normalizePermissions(raw))),
[],
);
// 主壳换账号 / 刷新权限后广播 <shortName>:session,这里重新读 localStorage。
// 同时监听本应用内同名 CustomEvent(SubAppLifecycle 转发),避免两个订阅点各写一套。
useEffect(() => {
const refresh = () => {
const s = readSession();
setRoleCodes(s?.roleCodes ?? []);
setRoleState(sessionRole(s?.roleCodes ?? []));
setPoints(initialPoints());
};
const bus = subappBus();
const name = shortName();
if (bus && name) bus.$on(busEvents(name).session, refresh);
window.addEventListener('uj:session-changed', refresh);
return () => {
if (bus && name) bus.$off(busEvents(name).session, refresh);
window.removeEventListener('uj:session-changed', refresh);
};
}, []);
const value = useMemo<AccessContextValue>(
() => ({
role,
roleCodes,
setRole,
matrix,
can: (resource, required = 'view') => {
// 与 host 版一致:门店审批与列表必须有精确 :view;其余走三段兜底。
if (required === 'view' && (resource === 'store:approve' || resource === 'store:list')) {
return points.has(`${resource}:view`);
}
return canByPoints(points, resource);
},
points,
canPoint: (p: string) => canPointByPoints(points, p),
loadPermissions,
applyLogin,
}),
[role, roleCodes, setRole, matrix, points, applyLogin, loadPermissions],
);
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;
}