-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathHasAccess.tsx
79 lines (64 loc) · 1.74 KB
/
HasAccess.tsx
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
import * as React from "react";
import { useEffect, useState, useContext, PropsWithChildren } from "react";
export interface UserPayload {
id: string;
roles: string[];
permissions: string[];
}
const LOCAL_STORAGE_KEY_USER = "__permifyUser";
export interface HasAccessProps {
roles?: string[];
permissions?: string[];
isLoading?: React.ReactElement;
renderAuthFailed?: React.ReactElement;
}
const HasAccess = ({
roles,
permissions,
isLoading,
renderAuthFailed,
children,
}: PropsWithChildren<HasAccessProps>) => {
const [hasAccess, setHasAccess] = useState(false);
const [checking, setChecking] = useState(false);
useEffect(() => {
const storedUser = JSON.parse(localStorage.getItem(LOCAL_STORAGE_KEY_USER));
if (!storedUser) {
console.log(
"No user provided to Permify! You should set user to perfom access check"
);
return;
}
setChecking(true);
// role check
if (roles && storedUser.roles && storedUser.roles.length > 0) {
const intersection = storedUser.roles.filter((role: string) =>
roles.includes(role)
);
if (intersection.length > 0) setHasAccess(true);
}
// permission check
if (
permissions &&
storedUser.permissions &&
storedUser.permissions.length > 0
) {
const intersection = storedUser.permissions.filter((permission: string) =>
permissions.includes(permission)
);
if (intersection.length > 0) setHasAccess(true);
}
setChecking(false);
}, [roles, permissions]);
if (!hasAccess && checking) {
return isLoading;
}
if (hasAccess) {
return <>{children}</>;
}
if (renderAuthFailed) {
return renderAuthFailed;
}
return null;
};
export default HasAccess;