forked from dpim/wf-react-app
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathPermissionsProxy.tsx
More file actions
50 lines (41 loc) · 1.4 KB
/
PermissionsProxy.tsx
File metadata and controls
50 lines (41 loc) · 1.4 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
import { permissionsMap, Permission } from './PermissionsMap'
interface Permissions {
[key: string]: boolean
}
function createPermissionsProxy<T extends object>(
target: T,
permissions: Permissions,
): T {
return new Proxy(target, {
get(obj, prop: string | symbol, receiver: any) {
const originalMethod = obj[prop as keyof T]
if (typeof originalMethod === 'function') {
return function (...args: any[]) {
const objectType = target.constructor.name
const methodName = prop.toString()
const methodPermissions = permissionsMap[objectType]?.[methodName]
// Check Permissisons
if (methodPermissions) {
const hasPermission = methodPermissions.permissions.every(
(permission) => permissions[permission],
)
if (!hasPermission) {
console.error(
`You do not have permission to execute ${objectType}.${methodName}`,
)
return // Prevent execution if permissions are insufficient
}
} else {
console.warn(
`No permissions defined for method: ${objectType}.${methodName}`,
)
}
// Call the original method
return (originalMethod as Function).apply(receiver, args)
}
}
return originalMethod
},
})
}
export default createPermissionsProxy