AccessProvider.tsx
5.15 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
144
145
146
147
import {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useState,
type ReactNode,
} from 'react';
import {
defaultMatrix,
roleLabels as seedRoleLabels,
type PermissionMatrix,
type ResourceKey,
type RoleKey,
} from '../model';
import { matrixToPoints } from '../backend/adapter';
import { defineProtocols, type AccessDeps } from '@venus/contracts';
import { protocols as bizProtocols } from '@/protocols';
import {
readPermCodes,
readSession,
shortName,
subappBus,
} from '../../../subapp';
import { busEvents } from '@venus/contracts';
/**
* 与 host 共读一份业务协议(@/protocols)。子应用只实现权限协议即可,
* 归一 / 角色解析 / can / canPoint 的规则在主壳与所有子应用同时生效。
*/
const accessProtocol = defineProtocols(bizProtocols).access;
const { normalizePermissions, resolveRole, can: canByProtocol, canPoint, basePoints } = accessProtocol;
/** 子应用的权限上下文同样喂给协议,业务规则里能拿到 points / roleLabels / profile。 */
const accessDeps = (points: Set<string>): AccessDeps => ({
points,
roleLabels: seedRoleLabels as Record<string, string>,
profile: {},
});
/**
* 子应用版 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 resolveRole(codes, accessDeps(new Set()));
}
function initialPoints(): Set<string> {
const next = new Set(normalizePermissions(readPermCodes()));
if (readSession()) basePoints({ ...accessDeps(next), hasSession: true }).forEach((p) => next.add(p));
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));
basePoints({ ...accessDeps(next), hasSession: true }).forEach((p) => next.add(p));
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('venus:session-changed', refresh);
return () => {
if (bus && name) bus.$off(busEvents(name).session, refresh);
window.removeEventListener('venus:session-changed', refresh);
};
}, []);
const value = useMemo<AccessContextValue>(
() => ({
role,
roleCodes,
setRole,
matrix,
can: (resource, required = 'view') => canByProtocol(resource, required, accessDeps(points)),
points,
canPoint: (p: string) => canPoint(p, accessDeps(points)),
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;
}