-
Notifications
You must be signed in to change notification settings - Fork 73
Expand file tree
/
Copy pathusePermissionCheck.ts
More file actions
37 lines (30 loc) · 1010 Bytes
/
usePermissionCheck.ts
File metadata and controls
37 lines (30 loc) · 1010 Bytes
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
import { useContext } from "react";
// Example context shape
interface AuthContextType {
roles?: string[];
permissions?: string[];
}
const AuthContext = React.createContext<AuthContextType>({});
// Hook options
interface UsePermissionCheckOptions {
throwOnUnauthorized?: boolean;
}
// Main hook
export function usePermissionCheck(
required: string | string[],
source?: { roles?: string[]; permissions?: string[] },
options?: UsePermissionCheckOptions
): boolean {
const context = useContext(AuthContext);
const userRoles = source?.roles ?? context.roles ?? [];
const userPermissions = source?.permissions ?? context.permissions ?? [];
const requiredArr = Array.isArray(required) ? required : [required];
// Check roles and permissions
const hasAccess =
requiredArr.some((r) => userRoles.includes(r)) ||
requiredArr.some((p) => userPermissions.includes(p));
if (!hasAccess && options?.throwOnUnauthorized) {
throw new Error("Unauthorized");
}
return hasAccess;
}