-
-
Notifications
You must be signed in to change notification settings - Fork 5.3k
/
Copy pathWithPermissions.tsx
94 lines (86 loc) · 2.85 KB
/
WithPermissions.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import { Children, ReactElement, ComponentType, createElement } from 'react';
import { Location } from 'react-router-dom';
import warning from '../util/warning';
import { useAuthenticated } from './useAuthenticated';
import usePermissionsOptimized from './usePermissionsOptimized';
export interface WithPermissionsChildrenParams {
permissions: any;
}
type WithPermissionsChildren = (
params: WithPermissionsChildrenParams
) => ReactElement;
export interface WithPermissionsProps {
authParams?: object;
children?: WithPermissionsChildren;
component?: ComponentType<any>;
location?: Location;
render?: WithPermissionsChildren;
staticContext?: object;
[key: string]: any;
}
const isEmptyChildren = children => Children.count(children) === 0;
/**
* After checking that the user is authenticated,
* retrieves the user's permissions for a specific context.
*
* Useful for Route components ; used internally by Resource.
* Use it to decorate your custom page components to require
* a custom role. It will pass the permissions as a prop to your
* component.
*
* You can set additional `authParams` at will if your authProvider
* requires it.
*
* @example
* import { Admin, CustomRoutes, WithPermissions } from 'react-admin';
*
* const Foo = ({ permissions }) => (
* {permissions === 'admin' ? <p>Sensitive data</p> : null}
* <p>Not sensitive data</p>
* );
*
* const customRoutes = [
* <Route path="/foo" element={
* <WithPermissions
* authParams={{ foo: 'bar' }}
* component={({ permissions, ...props }) => <Foo permissions={permissions} {...props} />}
* />
* } />
* ];
* const App = () => (
* <Admin>
* <CustomRoutes>{customRoutes}</CustomRoutes>
* </Admin>
* );
*/
const WithPermissions = (props: WithPermissionsProps) => {
const {
authParams,
children,
render,
component,
staticContext,
...rest
} = props;
warning(
(render && children && !isEmptyChildren(children)) ||
(render && component) ||
(component && children && !isEmptyChildren(children)),
'You should only use one of the `component`, `render` and `children` props in <WithPermissions>'
);
useAuthenticated(authParams);
const { permissions } = usePermissionsOptimized(authParams);
// render even though the usePermissions() call isn't finished (optimistic rendering)
if (component) {
return createElement(component, { permissions, ...rest });
}
// @deprecated
if (render) {
return render({ permissions, ...rest });
}
// @deprecated
if (children) {
return children({ permissions, ...rest });
}
};
export default WithPermissions as ComponentType<WithPermissionsProps>;