AccessProvider.tsx
2.91 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
import { createContext, useContext, useMemo, useState, type ReactNode } from 'react';
import {
checkAccess,
defaultMatrix,
roleLabels,
type PermissionMatrix,
type ResourceKey,
type RoleKey,
} from '../model';
import { getLoginSession, getUserPermCodes } from '../session';
interface AccessContextValue {
role: RoleKey;
setRole: (r: RoleKey) => Promise<void>;
matrix: PermissionMatrix;
can: (resource: ResourceKey, required?: 'view' | 'full') => boolean;
/** 当前账号持有的权限点集合(来自本地用户信息的 permCodes) */
points: Set<string>;
/** 按钮/操作级权限判定:是否拥有某个权限点 */
canPoint: (point: string) => boolean;
/** 本地用户信息更新后刷新权限点。 */
loadPermissions: (raw: unknown) => void;
}
const AccessContext = createContext<AccessContextValue | null>(null);
export function AccessProvider({ children }: { children: ReactNode }) {
const [role, setRoleState] = useState<RoleKey>(
() =>
getLoginSession()?.roleCodes.find((code): code is RoleKey =>
Object.hasOwn(roleLabels, code),
) ?? 'VIEWER',
);
const [matrix] = useState<PermissionMatrix>(defaultMatrix);
const [points, setPoints] = useState<Set<string>>(() => new Set(getUserPermCodes()));
// 角色变化时,重新读取本地用户信息中的 permCodes;不再使用模拟权限。
const setRole = async (r: RoleKey) => {
setRoleState(r);
setPoints(new Set(getUserPermCodes()));
};
const loadPermissions = (_raw: unknown) => {
setPoints(new Set(getUserPermCodes()));
};
const value = useMemo<AccessContextValue>(
() => ({
role,
setRole,
matrix,
can: (resource, required = 'view') => {
const storePermissions: Partial<Record<ResourceKey, { view: string; actions: string[] }>> =
{
'store.approve': {
view: 'store:approve:view',
actions: ['store:approve:pass', 'store:approve:reject'],
},
'store.listing': { view: 'store:list:view', actions: ['store:list:export'] },
'store.import': {
view: 'store:import:view',
actions: ['store:import:upload', 'store:import:submit'],
},
};
const permission = storePermissions[resource];
if (permission)
return (
points.has(permission.view) &&
(required === 'view' || permission.actions.some((code) => points.has(code)))
);
return checkAccess(matrix, role, resource, required);
},
points,
canPoint: (p: string) => points.has(p),
loadPermissions,
}),
[role, matrix, points],
);
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;
}