Raw
1 import { PropsWithChildren, useCallback, useMemo } from "react"
2 import {
3 buildPermission,
4 OPERATION_IMPLICATIONS,
5 parsePermission,
6 type Permission,
7 type PermissionOperation,
8 type PermissionResource,
9 type PermissionsContextValue,
10 type UserPolicy,
11 } from "../../lib/permissions"
12 import { PermissionsContext } from "./permissions-context"
13
14 interface PermissionsProviderProps extends PropsWithChildren {
15 /**
16 * The user's policy containing their permissions.
17 */
18 policy: UserPolicy | null
19 /**
20 * Whether the policy is currently being loaded.
21 */
22 isLoading?: boolean
23 /**
24 * Whether the RBAC feature flag is enabled. When `false`, every permission
25 * check resolves to `true`.
26 */
27 isRbacEnabled?: boolean
28 }
29
30 export const PermissionsProvider = ({
31 policy,
32 isLoading = false,
33 isRbacEnabled = true,
34 children,
35 }: PermissionsProviderProps) => {
36 const permissionsMap = useMemo(() => {
37 const index: Record<Permission, true> = Object.create(null)
38
39 for (const granted of policy?.permissions ?? []) {
40 const parsed = parsePermission(granted)
41 if (!parsed) {
42 continue
43 }
44
45 const { resource, operation } = parsed
46 const impliedOperations = OPERATION_IMPLICATIONS[operation] || [operation]
47
48 for (const impliedOperation of impliedOperations) {
49 index[buildPermission(resource, impliedOperation)] = true
50 }
51 }
52
53 return index
54 }, [policy])
55
56 const hasPermission = useCallback(
57 (permission: Permission): boolean => {
58 if (!isRbacEnabled) {
59 return true
60 }
61 return !!permissionsMap[permission]
62 },
63 [isRbacEnabled, permissionsMap]
64 )
65
66 const hasAnyPermission = useCallback(
67 (permissions: Permission[]): boolean => {
68 if (!isRbacEnabled) {
69 return true
70 }
71 if (!permissions?.length) {
72 return false
73 }
74
75 return permissions.some(hasPermission)
76 },
77 [isRbacEnabled, hasPermission]
78 )
79
80 const hasAllPermissions = useCallback(
81 (permissions: Permission[]): boolean => {
82 if (!isRbacEnabled) {
83 return true
84 }
85 if (!permissions?.length) {
86 return false
87 }
88
89 return permissions.every(hasPermission)
90 },
91 [isRbacEnabled, hasPermission]
92 )
93
94 const can = useCallback(
95 (resource: PermissionResource, operation: PermissionOperation): boolean => {
96 if (!isRbacEnabled) {
97 return true
98 }
99 return !!permissionsMap[buildPermission(resource, operation)]
100 },
101 [isRbacEnabled, permissionsMap]
102 )
103
104 const value: PermissionsContextValue = useMemo(
105 () => ({
106 policy,
107 isLoading,
108 hasPermission,
109 hasAnyPermission,
110 hasAllPermissions,
111 can,
112 }),
113 [policy, isLoading, hasPermission, hasAnyPermission, hasAllPermissions, can]
114 )
115
116 return (
117 <PermissionsContext.Provider value={value}>
118 {children}
119 </PermissionsContext.Provider>
120 )
121 }