|
1
|
import { useMemo } from "react" |
|
2
|
import type { PermissionResource } from "../lib/permissions" |
|
3
|
import { usePermissions } from "../providers/permissions-provider" |
|
4
|
|
|
5
|
/** |
|
6
|
* Hook that provides convenient permission checks for a specific resource. |
|
7
|
* Returns boolean flags for common CRUD operations. |
|
8
|
* |
|
9
|
* @param resource - The resource to check permissions for |
|
10
|
* @returns Object with permission flags and utility methods |
|
11
|
* |
|
12
|
* @example |
|
13
|
* ```tsx |
|
14
|
* const { canRead, canCreate, canUpdate, canDelete } = useResourcePermissions("customer") |
|
15
|
* |
|
16
|
* return ( |
|
17
|
* <div> |
|
18
|
* {canRead && <CustomerList />} |
|
19
|
* {canCreate && <Button>Create Customer</Button>} |
|
20
|
* </div> |
|
21
|
* ) |
|
22
|
* ``` |
|
23
|
*/ |
|
24
|
export const useResourcePermissions = (resource: PermissionResource) => { |
|
25
|
const { can, isLoading } = usePermissions() |
|
26
|
|
|
27
|
return useMemo( |
|
28
|
() => ({ |
|
29
|
/** |
|
30
|
* Whether the user can view/list this resource. |
|
31
|
*/ |
|
32
|
canRead: can(resource, "read"), |
|
33
|
|
|
34
|
/** |
|
35
|
* Whether the user can create new instances of this resource. |
|
36
|
*/ |
|
37
|
canCreate: can(resource, "create"), |
|
38
|
|
|
39
|
/** |
|
40
|
* Whether the user can update existing instances of this resource. |
|
41
|
*/ |
|
42
|
canUpdate: can(resource, "update"), |
|
43
|
|
|
44
|
/** |
|
45
|
* Whether the user can delete instances of this resource. |
|
46
|
*/ |
|
47
|
canDelete: can(resource, "delete"), |
|
48
|
|
|
49
|
/** |
|
50
|
* Check a specific operation on this resource. |
|
51
|
*/ |
|
52
|
can: (operation: "read" | "create" | "update" | "delete") => |
|
53
|
can(resource, operation), |
|
54
|
|
|
55
|
/** |
|
56
|
* The resource being checked. |
|
57
|
*/ |
|
58
|
resource, |
|
59
|
|
|
60
|
/** |
|
61
|
* Whether permissions are still loading. |
|
62
|
*/ |
|
63
|
isLoading, |
|
64
|
}), |
|
65
|
[can, resource, isLoading] |
|
66
|
) |
|
67
|
} |
|
68
|
|
|
69
|
/** |
|
70
|
* Hook for checking customer-specific permissions. |
|
71
|
*/ |
|
72
|
export const useCustomerPermissions = () => useResourcePermissions("customer") |
|
73
|
|
|
74
|
/** |
|
75
|
* Hook for checking order-specific permissions. |
|
76
|
*/ |
|
77
|
export const useOrderPermissions = () => useResourcePermissions("order") |
|
78
|
|
|
79
|
/** |
|
80
|
* Hook for checking product-specific permissions. |
|
81
|
*/ |
|
82
|
export const useProductPermissions = () => useResourcePermissions("product") |
|
83
|
|
|
84
|
/** |
|
85
|
* Hook for checking inventory-specific permissions. |
|
86
|
*/ |
|
87
|
export const useInventoryPermissions = () => useResourcePermissions("inventory") |
|
88
|
|
|
89
|
/** |
|
90
|
* Hook for checking user management permissions. |
|
91
|
*/ |
|
92
|
export const useUserPermissions = () => useResourcePermissions("user") |